[英]CORS preflight request error ExpressJS and Angular
I am trying to create a simple login using an ExpressJS backend, just to test to see how this would work.我正在尝试使用 ExpressJS 后端创建一个简单的登录,只是为了测试它是如何工作的。 But for some weird reason an OPTIONS call is done on to my Angular front-end and throws a CORS error.
但是由于一些奇怪的原因,对我的 Angular 前端进行了 OPTIONS 调用,并引发了 CORS 错误。
The request headers of the OPTIONS call can be seen in the image below. OPTIONS 调用的请求标头如下图所示。
My ExpressJS Cors setup:我的 ExpressJS Cors 设置:
// There are 2 front-end applications, only the second is used now but it needs to work with both.
env.redirectURL = ['http://localhost:4200', 'http://localhost:5200'];
const app = express();
app.use(cors({ credentials: true, origin: env.redirectURL }));
In this code below I create a JWT token and send it to the front-end using redirection.在下面的代码中,我创建了一个 JWT 令牌并使用重定向将其发送到前端。 This then for some reason calls an "options" request on my front-end which fails.
然后由于某种原因,这在我的前端调用了一个“选项”请求,但失败了。
export default (req: Request, res: Response) => {
if (!req.user) {
if (env.logging) console.error('No user found!');
res.status(500).send();
return;
}
const expiresIn = 30 * 60 * 24 * 60000;
jwt.sign(req.user, env.jwt.secret, { expiresIn }, (err, token) => {
if (err) {
if (env.logging) console.error(err);
res.sendStatus(500); // Handle Error Better
} else {
res.cookie('token', token, {
sameSite: false,
httpOnly: true,
secure: env.jwt.secure,
expires: new Date(new Date().getTime() + expiresIn),
});
res.redirect(env.redirectURL[1]);
}
});
};
I have been stuck on this for multiple days now and tried to do the same thing months ago as well.我已经坚持了好几天了,几个月前我也试图做同样的事情。 I feel stupid for not being capable of figuring this out and this is my last resort.
我因为无法弄清楚这一点而感到愚蠢,这是我最后的手段。
It is very hard to fix this issue without debug.没有调试很难解决这个问题。
Could you try to replace this code?您可以尝试替换此代码吗?
// There are 2 front-end applications, only the second is used now but it needs to work with both.
env.redirectURL = ['http://localhost:4200', 'http://localhost:5200'];
const app = express();
app.use(cors({ credentials: true, origin: env.redirectURL }));
by经过
const allowedOrigins = ['http://localhost:4200', 'http://localhost:5200'];
app.use(cors({
origin: function (origin, callback) {
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
},
credentials: true,
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.