'How to fix CORS Error when using the Nest JS framework

I added cors package in the main.ts. but still it's throwing error. I don't understand why this error throwing can you pls explain how to properly handling cors issue.

Main.ts

  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.setBaseViewsDir(join(__dirname, '..', 'views'))
  app.setViewEngine('hbs')
  app.use(helmet());
  app.use(express.json({ limit: "50mb" }))
  app.use(express.urlencoded({ limit: "50mb" }))
  
  app.enableCors();

  // app.setGlobalPrefix('api/v1');

  // app.use(csurf({ cookie: false }));

  app.use(cookieParser());

Error

Access to XMLHttpRequest at 'http://localhost:3000' from origin 'http://localhost:4000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I referred many documentation. All documentation saying add enablecors() in main.ts file but it's throwing error



Solution 1:[1]

Have you tried this

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

Solution 2:[2]

You could do something like this

      const app = await NestFactory.create(AppModule);
      

      const options = {
        origin: "*",
        methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
        preflightContinue: false,
        optionsSuccessStatus: 204,
        credentials: true
      };
   
      app.enableCors(options);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sopheak Sek
Solution 2 Rahul Pal