首頁  >  文章  >  運維  >  Nginx設定跨域請求報錯Access-Control-Allow-Origin * 怎麼解決

Nginx設定跨域請求報錯Access-Control-Allow-Origin * 怎麼解決

WBOY
WBOY轉載
2023-05-11 23:10:125680瀏覽

前言

當出現403跨域錯誤的時候 no 'access-control-allow-origin' header is present on the requested resource,需要給nginx伺服器設定回應的header參數:

一、 解決方案

#只需要在nginx的設定檔中設定以下參數:

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;
 }
}

上面設定程式碼即可解決問題了,不想深入研究的,看到這裡就可以啦=-=

#二、解釋




##1. access-control-allow-origin

伺服器預設是不被允許跨域的。給nginx伺服器設定`access-control-allow-origin *`後,表示伺服器可以接受所有的請求來源(origin),即接受所有跨網域的請求。

2. access-control-allow-headers 是為了防止以下錯誤:

request header field content-type is not allowed by access-control-allow-headers in preflight response.
這個錯誤表示目前請求content-type的值不被支援。其實是我們發起了"application/json"的型別請求所導致的。這裡涉及到一個概念:預檢請求(preflight request),請看下面"預檢請求"的介紹。

3. access-control-allow-methods 是為了防止以下錯誤:


content-type is not allowed by access-control -allow-headers in preflight response.

4.給options 添加204的返回,是為了處理在發送post請求時nginx依然拒絕訪問的錯誤

發送"預檢請求"時,需要用到方法options ,所以伺服器需要允許該方法。

三、 預檢請求(preflight request)


#其實上面的配置涉及到了一個w3c標準:cros,全名為跨域資源共享(cross -origin resource sharing),它的提出就是為了解決跨域請求的。

跨網域資源共享(cors)標準新增了一組 http 首部字段,允許伺服器宣告哪些來源站有權限存取哪些資源。另外,規範要求,對那些可能對伺服器資料產生副作用的http 請求方法(特別是get 以外的http 請求,或搭配某些mime 類型的post 請求),瀏覽器必須先使用options 方法發起一個預檢請求( preflight request),從而獲知服務端是否允許該跨域請求。伺服器確認允許之後,才發起實際的 http 請求。在預檢請求的回傳中,伺服器端也可以通知用戶端,是否需要攜帶身分憑證(包括 cookies 和 http 認證相關資料)。

其實content-type欄位的型別為application/json的請求就是上面所說的搭配某些mime 型別的post 請求,cors規定,content-type不屬於下列mime型別的,都屬於預檢請求:

###application/x-www-form-urlencoded###multipart/form-data###text/plain########### ##所以application/json的請求會在正式通信之前,增加一次"預檢"請求,這次"預檢"請求會帶上頭部資訊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
... 省略了一些
###伺服器回應時,傳回的頭部資訊如果不包含access-control-allow-headers: content-type則表示不接受非預設的的content-type。即出現下列錯誤:#########request header field content-type is not allowed by access-control-allow-headers in preflight response.######

以上是Nginx設定跨域請求報錯Access-Control-Allow-Origin * 怎麼解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除