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