2

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

Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
hari prasanth
  • 716
  • 1
  • 15
  • 35

3 Answers3

2

Have you tried this

const app = await NestFactory.create(AppModule, {
  cors: true,
});
Sopheak Sek
  • 152
  • 1
  • 8
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);
Rahul Pal
  • 476
  • 3
  • 10
1

Just add the "origin" property.

const app = await NestFactory.create(AppModule);

app.enableCors({
  origin: "localhost:4000",
});
Alex Shepel
  • 381
  • 5
  • 7