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代理,能获得结果。



|