问题:
在express框架下,已经加了跨域的请求头设置,但是,发现,option请求能通过,post请求因为跨域问题被拦截。查看post请求头部,确实缺失了Access-Control-Allow-Origin头部信息。
其他可能的影响因素
(以下情况,来自其他网友博客说法,暂时精力有限,均未验证是否对错):
- “Access-Control-Allow-Origin”: *
有说法称该头部不能设置为 * - “Access-Control-Allow-Credentials”: true
前端也设置了 xhr.withCredentials = true;
“ 如果要发送Cookie,Access-Control-Allow-Origin就不能设为星号,必须指定明确的、与请求网页一致的域名。同时,Cookie依然遵循同源政策,只有用服务器域名设置的Cookie才会上传,其他域名的Cookie并不会上传,且(跨源)原网页代码中的document.cookie也无法读取服务器域名下的Cookie。”
https://blog.csdn.net/java_green_hand0909/article/details/78740765 - ‘Content-Type’: ‘application/json;charset=utf-8’
某某某情况下Content-Type不支持设置
最终解决方案:
express允许跨域的代码必须放在路由前面。
// 允许跨域
app.all('*', function(req, res, next) {
console.log(req.headers.origin)
console.log(req.environ)
res.header("Access-Control-Allow-Origin", req.headers.origin);
// 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("Access-Control-Allow-Credentials","true");
res.header("X-Powered-By",' 3.2.1')
if(req.method === "OPTIONS") res.send(200);/*让options请求快速返回*/
else next();
});
app.use('/router1', router1);
需要将允许跨域的请求代码放在所有的路由前面,因为请求被express接受到的时候,拦截的顺序是根据自己写的代码路由顺序决定的,一旦满足拦截条件,如果不执行next()方法,则就不会继续把请求发送给下一个路由拦截器。
https://blog.csdn.net/hbiao68/article/details/84883537