nginx解決跨域問題

當出現403跨域錯誤的時候 No 'Access-Control-Allow-Origin' header is present on the requested resource,須要給Nginx服務器配置響應的header參數:
1、 解決方案
只須要在Nginx的配置文件中配置如下參數:json

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

上面配置代碼便可解決問題了,不想深刻研究的,看到這裏就能夠啦=-=
2、 解釋segmentfault

  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');

原文地址:
http://www.javashuo.com/article/p-zlhfinyg-gq.html
https://blog.csdn.net/HQB421/article/details/80505073app

相關文章
相關標籤/搜索