'Enable Cors in 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();


Solution 1:[1]

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

Solution 2:[2]

main.ts

const app = await NestFactory.create(AppModule);
app.enableCors({
    origin: '*',
    methods: 'GET, PUT, POST, DELETE',
    allowedHeaders: 'Content-Type, Authorization',
});
await app.listen(3000);

Solution 3:[3]

You can make use of cors npm module. Install cors by running the command
npm install cors --save

After installation, in your main.ts file paste the below line.

app.use(cors());

Solution 4:[4]

An alternative to CORS headers is to standup a webserver such as Nginix on your computer and proxy all your requests through it, forwarding to the appropriate port based on a url root. This is how things are normally approached in the real world as the CORS headers are relatively new and can open security holes you may not want by default.

This solves the fundamental problem that is your application is running on a different Origin (protocol + domain + port) than the api you want to access.

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 Rajeev Radhakrishnan
Solution 2 Nicolas Bodin-Ripert
Solution 3 Sasuke Uchiha
Solution 4 Deadron