NestJS enable cors in production

前端 未结 5 1225
萌比男神i
萌比男神i 2021-02-03 21:49

I\'ve enabled CORS in my NestJS app following the official tutorial, so my main.ts looks like the following:

import { FastifyAdapter, NestFactory }          


        
相关标签:
5条回答
  • 2021-02-03 22:08

    If you are running NestJs with graphql you will run into a problem where Apollo server will override the CORS setting see link. This below fixed the problem. I wasted 8 hrs of my life on this. :-( I hope you see this and you don't do that. see link and link

            GraphQLModule.forRoot({
                debug: process.env.NODE_ENV !== 'production',
                playground: process.env.NODE_ENV !== 'production',
                typePaths: ['./**/*.graphql'],
                installSubscriptionHandlers: true,
                context: ({req}) => {
                    return {req};
                },
                cors: {
                    credentials: true,
                    origin: true,
                },
            }),
    

    then in your main.ts:

            app.enableCors({
                origin: true,
                methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
                credentials: true,
            });
    
    0 讨论(0)
  • 2021-02-03 22:09

    Sad to know that you also tried:

    const app = await NestFactory.create(ApplicationModule);
    app.enableCors();
    await app.listen(3000);
    

    And it's still not working.


    Ensure that on your server side you have cors enabled, which should be something like this:

    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');
      next();
    });
    

    And also ensure that your browser is cors supported. If all these still doesn't work, I will advice you download Allow-Control-Allow-Origin extension for Chrome, it should fix your issue.

    0 讨论(0)
  • 2021-02-03 22:10

    Try to use an approach described in here https://docs.nestjs.com/techniques/security#cors

    const app = await NestFactory.create(ApplicationModule);
    app.enableCors();
    await app.listen(3000);
    
    0 讨论(0)
  • 2021-02-03 22:10

    I was able to get it working by giving my own origin function. The complete enableCors function would be like for NestJS or any NodeJS server like:

    var whitelist = ['https://website.com', 'https://www.website.com'];
    app.enableCors({
    origin: function (origin, callback) {
      if (whitelist.indexOf(origin) !== -1) {
        console.log("allowed cors for:", origin)
        callback(null, true)
      } else {
        console.log("blocked cors for:", origin)
        callback(new Error('Not allowed by CORS'))
      }
    },
    allowedHeaders: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Observe',
    methods: "GET,PUT,POST,DELETE,UPDATE,OPTIONS",
    credentials: true,
    });
    

    and the appOptions if you are using NestJS Express:

    const app = await NestFactory.create<NestExpressApplication>(AppModule);
    
    0 讨论(0)
  • 2021-02-03 22:18

    Somehow the issue was compiling it using npm run webpack. If I compile it using prestart:prod then it will work.

    Thanks @georgii-rychko for suggesting it via comments.

    0 讨论(0)
提交回复
热议问题