In this post, we will learn how to enable CORS in the NestJS application.
You can enable CORS in your NestJS project by calling .enableCors()
method of your app
instance:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);
}
bootstrap();
If we make a request even in the browser we should face `Access-Control-Allow-Origin` header:
Without running this method the result will be another:
You can enable CORS in your NestJS project by passing an object as a second argument to .create
function. Just set cors
field value to true in this object:
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: true
});
// app.enableCors();
await app.listen(3000);
}
You can see it is easy to configure CORS for your NestJS application. If you want flexible set-up just pass CORS object to .enableCors
method or set it into cors
parameter.