skip to Main Content

Why do I get cors error and invalid headers when requesting from frontend http://localhost:3000?

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

Nignx

    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;


    }

Postman result header:

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

Sometimes I get response headers: 0.
I’ve been agonizing for 5 hours and I don’t know how to fix it.

2

Answers


  1. Chosen as BEST ANSWER

    I found the problem. This is very stupid -

    I changed the line

     const app = await NestFactory.create(AppModule, { cors: true });
    

    on

     const app = await NestFactory.create(AppModule);
    

    It rewrote the Origin header


  2. You are requesting the page at http://localhost:3000 but your nginx config is changing it to http://localhost:4000 via proxy_pass. Have you tried

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

    to match your nginx config?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search