天天看點

【Nginx】第十二節 配置跨域通路

author:咔咔

先看一下哪些都屬于跨域

【Nginx】第十二節 配置跨域通路

跨域:這個意思就是在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.

繼續閱讀