Ajax 跨域访问post 请求,但是在服务器却得到的总是options请求 (req.method==‘OPTIONS’)

原因有俩:

1.跨域

2.此post请求的 content-type不是one of the “application/x-www-form-urlencoded,multipart/form-data, or text/plain”

解决办法:

添加代码

if (req.method === 'OPTIONS') {

console.log('!OPTIONS');

var headers = {};

// IE8 does not allow domains to be specified, just the *

// headers["Access-Control-Allow-Origin"] = req.headers.origin;

headers["Access-Control-Allow-Origin"] = "*";

headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";

headers["Access-Control-Allow-Credentials"] = false;

headers["Access-Control-Max-Age"] = '86400'; // 24 hours

headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";

res.writeHead(200, headers);

res.end();

} else {

//...other requests

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容