nginx解決跨域問題

當出現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"的類型請求導致的。
  3. Access-Control-Allow-Methods 是爲了防止出現以下錯誤:
    Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

  4. 給OPTIONS 添加 204的返回,是爲了處理在發送POST請求時Nginx依然拒絕訪問的錯誤
    發送"預檢請求"時,需要用到方法 OPTIONS ,所以服務器需要允許該方法。

PHP解決跨域問題,加入header頭:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header('Access-Control-Allow-Headers:x-requested-with,content-type');

原文地址:
https://segmentfault.com/a/1190000012550346
https://blog.csdn.net/HQB421/article/details/80505073

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章