當(dāng)出現(xiàn)403跨域錯(cuò)誤的時(shí)候 no 'access-control-allow-origin' header is present on the requested resource
,需要給nginx服務(wù)器配置響應(yīng)的header參數(shù):
一、 解決方案
只需要在nginx的配置文件中配置以下參數(shù):
location / { add_header access-control-allow-origin *; add_header access-control-allow-methods 'get, post, options'; add_header access-control-allow-headers 'dnt,x-mx-reqtoken,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,authorization'; if ($request_method = 'options') { return 204; } }
上面配置代碼即可解決問(wèn)題了,不想深入研究的,看到這里就可以啦=-=
二、 解釋
1. access-control-allow-origin
服務(wù)器默認(rèn)是不被允許跨域的。給nginx服務(wù)器配置`access-control-allow-origin *`后,表示服務(wù)器可以接受所有的請(qǐng)求源(origin),即接受所有跨域的請(qǐng)求。
2. access-control-allow-headers 是為了防止出現(xiàn)以下錯(cuò)誤:
request header field content-type is not allowed by access-control-allow-headers in preflight response.
這個(gè)錯(cuò)誤表示當(dāng)前請(qǐng)求content-type的值不被支持。其實(shí)是我們發(fā)起了"application/json"的類型請(qǐng)求導(dǎo)致的。這里涉及到一個(gè)概念:預(yù)檢請(qǐng)求(preflight request),請(qǐng)看下面"預(yù)檢請(qǐng)求"的介紹。
3. access-control-allow-methods 是為了防止出現(xiàn)以下錯(cuò)誤:
content-type is not allowed by access-control-allow-headers in preflight response.
4.給options 添加 204的返回,是為了處理在發(fā)送post請(qǐng)求時(shí)nginx依然拒絕訪問(wèn)的錯(cuò)誤
發(fā)送"預(yù)檢請(qǐng)求"時(shí),需要用到方法 options ,所以服務(wù)器需要允許該方法。
三、 預(yù)檢請(qǐng)求(preflight request)
其實(shí)上面的配置涉及到了一個(gè)w3c標(biāo)準(zhǔn):cros,全稱是跨域資源共享 (cross-origin resource sharing),它的提出就是為了解決跨域請(qǐng)求的。
跨域資源共享(cors)標(biāo)準(zhǔn)新增了一組 http 首部字段,允許服務(wù)器聲明哪些源站有權(quán)限訪問(wèn)哪些資源。另外,規(guī)范要求,對(duì)那些可能對(duì)服務(wù)器數(shù)據(jù)產(chǎn)生副作用的http 請(qǐng)求方法(特別是 get 以外的 http 請(qǐng)求,或者搭配某些 mime 類型的 post 請(qǐng)求),瀏覽器必須首先使用 options 方法發(fā)起一個(gè)預(yù)檢請(qǐng)求(preflight request),從而獲知服務(wù)端是否允許該跨域請(qǐng)求。服務(wù)器確認(rèn)允許之后,才發(fā)起實(shí)際的 http 請(qǐng)求。在預(yù)檢請(qǐng)求的返回中,服務(wù)器端也可以通知客戶端,是否需要攜帶身份憑證(包括 cookies 和 http 認(rèn)證相關(guān)數(shù)據(jù))。
其實(shí)content-type字段的類型為application/json的請(qǐng)求就是上面所說(shuō)的搭配某些 mime 類型的 post 請(qǐng)求,cors規(guī)定,content-type不屬于以下mime類型的,都屬于預(yù)檢請(qǐng)求:
application/x-www-form-urlencoded
multipart/form-data
text/plain
所以 application/json的請(qǐng)求 會(huì)在正式通信之前,增加一次"預(yù)檢"請(qǐng)求,這次"預(yù)檢"請(qǐng)求會(huì)帶上頭部信息 access-control-request-headers: content-type:
options /api/test http/1.1 origin: http://foo.example access-control-request-method: post access-control-request-headers: content-type ... 省略了一些
服務(wù)器回應(yīng)時(shí),返回的頭部信息如果不包含access-control-allow-headers: content-type則表示不接受非默認(rèn)的的content-type。即出現(xiàn)以下錯(cuò)誤:
request header field content-type is not allowed by access-control-allow-headers in preflight response.