1. 程式人生 > >【Nginx】第十二節 配置跨域訪問

【Nginx】第十二節 配置跨域訪問

author:咔咔

wechat:fangkangfk

 

先看一下哪些都屬於跨域

 

跨域:這個意思就是在A域名下的業務,需要請求到B域名的程式碼,這就這簡單的跨域

 

在正常的業務中,很難避免跨域,所以我們就需要使用nginx配置一下

 

location / {  
  add_header Access-Control-Allow-Origin *;
  add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
  add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
}

 

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.

傳送”預檢請求”時,需要用到方法 OPTIONS ,所以伺服器需要允許該方法。