CORS 中的POST and OPTIONS 请求

var req = new XMLHttpRequest();
  req.open('post', 'http://127.0.0.1:3001/user', true);
  req.setRequestHeader('Content-Type', 'application/json');
  req.send('{"name":"tobi","species":"ferret"}');

此Ajax 跨域访问post 请求,但是在服务器却得到的总是options请求 (req.method==‘OPTIONS’) 不知为何啊?

原因:

因为此post请求的 content-type不是one of the “application/x-www-form-urlencoded, multipart/form-data, or text/plain”, 所以Preflighted requests被发起。“preflighted” requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send.然后得到服务器response许可之后,res.set(‘Access-Control-Allow-Origin’, ‘http://127.0.0.1:3000’);res.set(‘Access-Control-Allow-Methods’, ‘GET, POST, OPTIONS’);res.set(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type’);再发起其post请求。https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS


查找原因是浏览器对简单跨域请求和复杂跨域请求的处理区别。

XMLHttpRequest会遵守同源策略(same-origin policy). 也即脚本只能访问相同协议/相同主机名/相同端口的资源, 如果要突破这个限制, 那就是所谓的跨域, 此时需要遵守CORS(Cross-Origin Resource Sharing)机制。

那么, 允许跨域, 不就是服务端设置Access-Control-Allow-Origin: *就可以了吗? 普通的请求才是这样子的, 除此之外, 还一种叫请求叫preflighted request。

preflighted request在发送真正的请求前, 会先发送一个方法为OPTIONS的预请求(preflight request), 用于试探服务端是否能接受真正的请求,如果options获得的回应是拒绝性质的,比如404\403\500等http状态,就会停止post、put等请求的发出。

那么, 什么情况下请求会变成preflighted request呢? 

1、请求方法不是GET/HEAD/POST
2、POST请求的Content-Type并非application/x-www-form-urlencoded, multipart/form-data, 或text/plain
3、请求设置了自定义的header字段

上面请求中设置了自定义的headers字段,出现了option请求。把自定义headers字段删掉后,只剩下get请求:

[javascript]  view plain  copy
  1. ajaxRequestGet: function (lastPath, requestParams, successFun) {  
  2.             $.ajax({  
  3.                 url : this.baseUrl+lastPath,  
  4.                 type : "get",  
  5.                 data: requestParams,  
  6.                 success : function(data){  
  7.                     successFun(data);  
  8.                 }  
  9.             });  
  10.         },  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值