CORS 中的POST and OPTIONS 请求
发布于 11 年前 作者 smalltiger 41706 次浏览 最后一次编辑是 8 年前
  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’) 不知为何啊?

4 回复

哦, 知道了. 因为此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

此例子是从3000端口域向3001端口域发request.

其实这里还存在一个问题,如果服务器不支持 prefight 的 options 请求,这个请求也会死掉。 http://hi.barretlee.com/2014/08/19/post-method-change-to-options/

@barretlee 那这样的话是不是要修改content-type为上面三个的其中一个?

回到顶部