我目前正在开发一个预订系统,我使用的身份验证是 JWT 并将其保存在我的 cookie 中。但是,我遇到了这样的关于 cors 的错误。
guestinfo:1 Access to fetch at 'https://localhost:4000/auth/login' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'
app.use(function (req: Request, res: Response, next: NextFunction) {
res.header('Access-Control-Allow-Origin', [
'https://127.0.0.1:3000/',
'https://localhost:3000/',
'https://127.0.0.1:3000',
'https://localhost:3000',
]);
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept',
);
next();
});
app.enableCors({
origin: [
'https://127.0.0.1:3000/',
'https://localhost:3000/',
'https://127.0.0.1:3000',
'https://localhost:3000',
],
credentials: true,
// methods: ['GET', 'POST'],
// allowedHeaders: ['Content-Type', 'Authorization'],
// maxAge: 86400,
});
await app.listen(4000);
const login = async () => {
const requestOptions = {
credentials: 'include',
withCredentials: true,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
path: '/',
body: JSON.stringify({
id: "ID",
password: "PASSWORD"
})
};
我尝试过凭据、https、httpOnly、安全、sameSite、过期选项。但这些都不起作用,仍然进去了。 在我看来,这个问题是“access-control-allow-origin”。但没有改变。
如何解决这个错误?请帮助我。
不需要设置
res.header
,只需使用app.enableCors
即可设置cors配置。我怀疑这两个配置是冲突的,请使用app.enableCors
确保您提供
origin
和允许的 methods
。
这应该有效:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: [
'https://127.0.0.1:3000/',
'https://localhost:3000/',
'https://127.0.0.1:3000',
'https://localhost:3000',
],
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
credentials: true,
});
await app.listen(4000);
}
bootstrap();