CNode

CORS 中的POST and OPTIONS 请求

Ssmalltiger发布于13 年前最后回复11 年前4 回复43112 浏览0 收藏
  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)

S
smalltiger#1·13 年前

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

S
smalltiger#2·13 年前

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

B
barretlee#3·12 年前

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

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