记录一个 Node 的坑
新手接触 Node 不到一个月,遇到了很多坑
后端代码是这样写的:
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
然而前端每次发送 AJAX 跨域请求时都收不到结果,错误信息为网关超时
XMLHttpRequest cannot load http://111.111.111.111:8089/login_service. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested resource. Origin
'http://111.111.111.111' is therefore not allowed access. The response had HTTP
status code 504.
后来发现前端使用 CORS 请求时content-type取值为application/json; charset=utf-8,也就是说发送跨域请求时会发送 OPTIONS 预检请求,而我没有对设置 OPTIONS 路由,因此成功入坑。后来把后端代码改为了
app.all('*',function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (req.method == 'OPTIONS') {
console.log('you can do that!!');
res.send(200); // 让 options 请求快速返回
} else {
next();
}
});
写在最后
从坑中出来了,颇有感慨。顺便记录了一下对 CORS 跨域的探索,可能是知识盲点太多所以入坑太多,Node 的路上你遇到了哪些坑?求各位告知。