Nest js - 关于“access-control-allow-origin”的 Cors 错误

问题描述 投票:0回答:1

我目前正在开发一个预订系统,我使用的身份验证是 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'

Nest JS 代码

  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”。但没有改变。

如何解决这个错误?请帮助我。

reactjs cookies cors nest
1个回答
0
投票

不需要设置

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();

© www.soinside.com 2019 - 2024. All rights reserved.