1. 程式人生 > >nginx 解決AJAX 跨域問題。

nginx 解決AJAX 跨域問題。

設置 列表 eight origin localhost 技術 log 3-9 ces

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

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

技術分享

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

技術分享

技術分享

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

技術分享技術分享

第三步:修改nginx配置文件

技術分享

配置代碼:

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代理,能獲得結果。

技術分享

技術分享

技術分享







nginx 解決AJAX 跨域問題。