为什么 CORS 在 NestJS APP + NGINX 中不起作用?

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

为什么从前端 http://localhost:3000 请求时会出现 cors 错误和无效标头?

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  useContainer(app.select(AppModule), { fallbackOnErrors: true });

  const configService = app.get(ConfigService<AllConfigType>);

  app.enableShutdownHooks();
  app.setGlobalPrefix(
    configService.getOrThrow('app.apiPrefix', { infer: true }),
    {
      exclude: ['/'],
    },
  );
  app.enableVersioning({
    type: VersioningType.URI,
  });
  app.enableCors({
    origin: 'http://localhost:3000',
    credentials: true,
  });
  app.useGlobalPipes(new ValidationPipe(validationOptions));
  app.useGlobalInterceptors(
    // ResolvePromisesInterceptor is used to resolve promises in responses because class-transformer can't do it
    // https://github.com/typestack/class-transformer/issues/549
    new ResolvePromisesInterceptor(),
    new ClassSerializerInterceptor(app.get(Reflector)),
  );

  const options = new DocumentBuilder()
    .setTitle('API')
    .setDescription('API docs')
    .setVersion('1.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('docs', app, document);

  await app.listen(configService.getOrThrow('app.port', { infer: true }));
}
void bootstrap();

尼格克斯

    location / {
        proxy_pass http://localhost:4000; # Порт на котором запускается ваше No>
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header Access-Control-Allow-Origin http://localhost:3000;


    }

邮递员结果标题:

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: tru

有时我会收到响应标头:0。 我已经苦恼了5个小时了,我不知道如何解决。

nginx cors nestjs
1个回答
0
投票

您正在请求位于

http://localhost:3000
的页面,但您的 nginx 配置正在通过
http://localhost:4000
将其更改为
proxy_pass
。你试过吗

  app.enableCors({
    origin: 'http://localhost:4000',
    credentials: true,
  });

匹配您的 nginx 配置?

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