nginx配置ajax请求跨域

首先通过mozilla文档了解跨域原理:

web跨域的方式有几种,常见的方案有web服务后端代码层级解决与nginx配置层面解决,这里我以nginx配置层面为例。

一般浏览器跨域请求的时候会先发起option预检测请求,当请求得到确认后,才开始真正发送请求。

因此,首先应该解决预请求的跨域问题,以下是nginx针对预请求的配置:

HTTP 204 成功状态响应码表示该请求已经成功了,但是客户端客户不需要离开当前页面。默认情况下 204 响应是可缓存的。一个 ETag 标头包含在此类响应中。

前端使用jquery发起ajax跨域携带cookie的请求代码:

效果:

接着在nginx配置正式请求的跨域:

重启nginx后,正式请求效果:

nginx配置内容:

location / {
        if ($request_method = 'OPTIONS') {
          add_header 'Access-Control-Allow-Origin' 'https://test.xx.com';
          add_header Access-Control-Max-Age 1728000;
          add_header 'Access-Control-Allow-Credentials' 'true';
          add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
          add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
          add_header Content-Type' 'text/plain; charset=utf-8';
          add_header Content-Length 0;
          return 204;
        }
        add_header 'Access-Control-Allow-Origin' 'https://test.xx.com';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
        client_max_body_size 20m;
        proxy_pass  http://xxx.xxx.10.200:8095;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值