nginx 解決AJAX 跨域問題。


AJAX跨域的問題很常見,有較多的解決辦法如:jsonp,設置服務端允許跨域,給請求加代理等等解決方式,我項目中常用node.js搭建中間代理的方式解決。下面我將嘗試采用nginx做代理的方式解決跨域的問題。

第一步:搭建Server API,其中未設置允許跨域。get方法,返回英雄列表。(http://localhost:8081/heroes

image

第二步:寫頁面測試ajax請求(http://localhost:8081/heroes),結果顯示跨域了。

image

image

順便說一下:如果要修改服務端只需要設置如下:

imageimage

第三步:修改nginx配置文件

image

配置代碼:

        location = /heroes {
             add_header 'Access-Control-Allow-Origin' '*';
             add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
             add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
             add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
                proxy_pass http://localhost:8081;
         }

第四步:測試ajax請求,這次將第二步中的8081改成80,讓ajax的請求被ngnix代理,能獲得結果。

image

image

image








免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM