首页 > 代码库 > CORS 中的POST and OPTIONS 请求

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

CORS 中的POST and OPTIONS 请求