NestJS enable cors in production

前端 未结 5 1235
萌比男神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: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(AppModule);
    

提交回复
热议问题