ajax跨域请求 nginx反向代理配置跨域

$.ajax({
		type: "POST",
		url: "http://www.dayangtuo247.xyz/write",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
		//············
}

在postman中,发送post请求正常,而在浏览器中发送post请求报错,查看信息为

Access to XMLHttpRequest at ‘xxx’ from origin ‘xxx’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

原因:浏览器发送post请求会事先发送一次预检请求(OPTIONS请求),而postman等测试软件并不会发送该请求,因此浏览器报错而postman软件不报错

触发预检请求的三类条件

  1. 默认情况下,跨域请求只支持GET,HEAD,POST方法,如果不是这三个请求方法(比如:PUT、DELETE、CONNECT、OPTIONS、TRACE和PATCH),那么将触发预检请求
  2. 默认情况下,浏览器跨域请求时,会自动添加的请求头(HOST,Referer,Connection、Accept、User-Agent,Accept-Languange,Accept-Encoding,Accept-Charset和Content-Type),这些请求中还有其他请求头时,那么将触发预检请求。
  3. 如1、2所说的情况排除在外的条件下,跨域请求是,浏览器支持的Content-Type值为application/x-www-form-urlencoded,multipart/form-data和text/plain。如果是其他数据类型(如application/json,text/xml…),那么将触发预检请求。
解决办法

nginx中location中插入如下代码以回应预检请求

if ($request_method = 'OPTIONS') {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Max-Age 1728000;
    add_header Access-Control-Allow-Methods 'GET,POST,OPTIONS,PUT,DELETE';    add_header Access-Control-Allow-Headers  'Token,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,ACCESS-TOKEN,x-file-name,Cookie';
    add_header Content-Type 'application/json;application/x-www-form-urlencoded;text/plain; charset=utf-8';
    add_header Content-Length 0 ;
    add_header Access-Control-Allow-Credentials true;
    return 204;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值