CORS 中的POST+JSON请求会先发送一个不带Cookie的OPTIONS(preflight request)请求

 
  1. var req = new XMLHttpRequest();

  2. req.open('post', 'http://127.0.0.1:3001/user', true);

  3. req.setRequestHeader('Content-Type', 'application/json');

  4. 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.         },  

猜你喜欢

转载自blog.csdn.net/u012501054/article/details/84591275