hari prasanth
hari prasanth

Reputation: 746

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

Upvotes: 3

Views: 12934

Answers (4)

Alex Shepel
Alex Shepel

Reputation: 696

Just add the origin property.

const app = await NestFactory.create(AppModule);

app.enableCors({
  origin: "localhost:4000",
});

Upvotes: 1

Davy Vos
Davy Vos

Reputation: 11

I just had the same issue with NestJS and an Angular client. While following an expressjs example I found the following line.

// some legacy browsers (IE11, various SmartTVs) choke on 204

Therefore set the success response for CORS to 200.

  app.enableCors({
    origin: 'http://localhost:4200',
    //allowedHeaders: 'Content-Type, Accept',
    //credentials: true,
    //methods: 'GET,PUT,POST,DELETE,OPTIONS',
    optionsSuccessStatus: 200
  });

In my situation this was the final step to the solution. One other issue I had is linked to this stackoverflow topic: https://stackoverflow.com/a/70375725/15190826. In short, when checking the origin header of the request make sure to not add trailing slashes.

To whoever might read this, I hope this helps you out.

Upvotes: -1

Rahul Pal
Rahul Pal

Reputation: 488

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

Upvotes: 4

Sopheak Sek
Sopheak Sek

Reputation: 162

Have you tried this

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

Upvotes: 2

Related Questions