experss 做小型服务器出现跨域问题

情况是这样的

我用express做一个小型的服务器来做我demo项目的一个接口

然后我就出现了跨域问题

然后我就

app.all('/*', function(req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Credentials', 'true');
// Set custom headers for CORS
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
// res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});

把这串代码丢到app.js上(注意,我是随便丢到了一个位置)

然后我前端就去请求那个接口,发现还是有跨域问题

感觉不对啊,上网搜了一下 都是说直接header允许跨域可以了,

但是为什么还是会出现跨域问题

然后我就去看别人的代码

然后发现然后这船代码的位置很重要

要放在你访问路由的那段代码之前

先允许跨域了 然后再访问路由

如果路由的代码放在前面那就直接进去路由然后没有到允许跨域那个地方就已经报错了

over  这些就是我想说的

所以也不知道是不是有什么问题  但是记录一下吧

原文地址:https://www.cnblogs.com/lwwen/p/9156115.html