最近玩了一下nodejs做服务端,出现了跨域问题,网上也找了很多文档,基本上使用以下方法都可以解决
// 我使用了express工具创建的项目
app.all("*",function (req,res,next) {
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Headers", "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();
console.log(req.method.toLowerCase());
if (req.method.toLowerCase() == 'options') {
res.send(200); // 让options尝试请求快速结束
} else {
next();
}
});
复制代码
但是,我前端在header中传递了token,没有使用解决跨域的插件,写法就得改为
app.all("*",function (req,res,next) {
res.header("Access-Control-Allow-Origin","*");
// 在这里加了一个token
res.header("Access-Control-Allow-Headers", "X-Requested-With,token");
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");
console.log(req.method.toLowerCase());
if (req.method.toLowerCase() == 'options') {
res.send(200); // 让options尝试请求快速结束
} else {
next();
}
});
复制代码