nginx 配置解決ajax跨域問題

問題描述:ajax 請求後臺服務器,瀏覽器報“ No 'Access-Control-Allow-Origin' header is present on the requested resource”錯誤,返回碼爲“200”,問題截圖如下:

解決方案:在nginx中server 的匹配規則中添加如下代碼:

 

            add_header 'Access-Control-Allow-Origin' *;
            add_header 'Access-Control-Allow-Credentials' 'true';
            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';

           

        

完整server配置如下:

server {
        listen       80;#你的端口
        server_name  172.162.52.77; #你nginx服務器ip

        access_log  logs/ykb.access.log main;
        error_log   logs/ykb.error.log;
        location  / {

            add_header 'Access-Control-Allow-Origin' *;
            add_header 'Access-Control-Allow-Credentials' 'true';
            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';
            proxy_pass   http://xx_url; //需要nginx將請求轉發到的ip
            proxy_redirect off;
            proxy_headers_hash_max_size 1024;
            proxy_headers_hash_bucket_size 512;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $http_x_forwarded_for;
            client_max_body_size 20m;

        }
}

 更多的ajax跨域問題可以查考:https://segmentfault.com/a/1190000012469713 

 

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