node.js+express 跨域问题加了请求头无效解决Access to XMLHttpRequest at 'xxxx'from'xxx'origin 'xxx' has been blocke

先吧以下代码复制下来

/*
解决跨域问题
/
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’)
if(req.method==“OPTIONS”) res.send(200);/让options请求快速返回/
else next();
});

放到app.js里面 的

var app = express();

这个下面 你可以ctrl+f查找下 切记放在这个下面
要在你注册路由的上面!!! 也就是

/*
     注册路由代码区域
*/
app.use('/', indexRouter);
app.use('/users', usersRouter);

这个的上面才有效果 不然无效!!!

猜你喜欢

转载自blog.csdn.net/qq_20472061/article/details/85003036