Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable Cors in NestJs

Tags:

cors

nestjs

I want to use a NestJs api, but I get the same error message in each fetch:

Access to fetch at 'http://localhost:3000/articles' from origin 'http://localhost:4200' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

My frontend is an Angular, where I have a simple fetch :

fetch('http://localhost:3000/articles')
    .then((res) => {
      console.log(res);
    });

I tried these options in my NestJs - but none of them seem to work:

Attempt A

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: true,
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    allowedHeaders: 'Content-Type, Accept',
  });
  await app.listen(3000);
}
bootstrap();

Attempt B

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  await app.listen(3000);
}
bootstrap();

Attempt C

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {cors: true});
  await app.listen(3000);
}
bootstrap();
like image 811
s grace Avatar asked Oct 22 '19 10:10

s grace


People also ask

What is CORS in node JS?

CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

How do I enable CORS in nginx?

To enable CORS on NGINX, you need to use the add_header directive and add it to the appropriate NGINX configuration file. to allow access from any domain.

How do you test CORS?

You can test your API's CORS configuration by invoking your API, and checking the CORS headers in the response. The following curl command sends an OPTIONS request to a deployed API.


1 Answers

On your main.ts, edit bootstrap function as follows to enable CORS

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

Or

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

This method helps you to pass additional params for cors

Read more about CORS here

like image 77
Rajeev Radhakrishnan Avatar answered Sep 17 '22 21:09

Rajeev Radhakrishnan