跳到主要内容
CNode

CORS 中的POST and OPTIONS 请求

社区
Ssmalltiger发布于 13 年前最后回复 11 年前
4431390
  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)

B
barretlee#312 年前

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

S
smalltiger#213 年前

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

S
smalltiger#113 年前

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

参与回复

登录后即可参与回复。登录