nginx 解决AJAX 跨域问题。

Posted 大头头大

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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







以上是关于nginx 解决AJAX 跨域问题。的主要内容,如果未能解决你的问题,请参考以下文章

跨域问题解决方案

解决ajax跨域问题

AJAX跨域问题解决方法——被调用方解决跨域

Nginx以及JSONP跨域ajax请求面试题

Nginx以及JSONP跨域ajax请求面试题

Nginx以及JSONP跨域ajax请求面试题