摘要:本文簡述了博主在開發(fā)過程中,需要跨域調(diào)試的時候,出現(xiàn)了 options 請求 forbidden 的問題,以及解決方法。
403 forbidden 解釋:
forbidden
you don't have permission to access / on this server.
additionally, a 500 internal server error error was encountered while trying to use an errordocument to handle the request.
403 forbidden 是http協(xié)議中的一個狀態(tài)碼(status code)。可以簡單的理解為沒有權(quán)限訪問此站點。
問題
在使用 spring cloud 的項目中,本地跨域調(diào)試發(fā)現(xiàn) post 請求轉(zhuǎn)為了 options 請求,并且服務(wù)端拒絕訪問,其實是 cors 請求的問題。
cors 請求分為2類: 簡單請求 和 非簡單請求。兩者主要的區(qū)分點在于:
1: 請求方法為 head, get, post;
2: http 頭信息為以下幾個: accept, accept-language,content-language, last-event-id,content-type (值為 application/x-www-form-urlencoded、multipart/form-data、text/plain)。
只要滿足以上兩點,則為簡單請求;否則為非簡單請求。
簡單請求的處理方式是瀏覽器直接發(fā)送 cors 請求。非簡單請求的處理方式是瀏覽器發(fā)送預(yù)檢請求,表示詢問服務(wù)器當(dāng)前的域名是否可以訪問正常服務(wù)器,如果可以訪問,則發(fā)送正常的請求到服務(wù)器;否則報錯。
現(xiàn)在確定遇到的問題就是在 cors 請求預(yù)檢的時候發(fā)現(xiàn)域名不在服務(wù)器端的白名單里面,所以需要修改服務(wù)端的請求返回報文。
解決方案
在網(wǎng)關(guān)中添加下面的過濾器,在每次請求返回報文中添加報文頭,即可正常訪問
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@component public class corsfilter implements filter { @override public void dofilter(servletrequest req, servletresponse res, filterchain chain) throws ioexception, servletexception { httpservletresponse response = (httpservletresponse) res; response.setheader( "access-control-allow-origin" , "*" ); response.setheader( "access-control-allow-methods" , "post, get, put, options, delete, patch" ); response.setheader( "access-control-max-age" , "3600" ); response.setheader( "access-control-allow-headers" , "origin, x-requested-with, content-type, accept" ); response.setheader( "access-control-expose-headers" , "location" ); chain.dofilter(req, res); } @override public void init(filterconfig filterconfig) {} @override public void destroy() {} } |
參考文章:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://1csh1.github.io/2017/11/06/spring-cloud-options-forbidden/