📜  nestjs cors origin - Javascript (1)

📅  最后修改于: 2023-12-03 15:33:05.976000             🧑  作者: Mango

NestJS CORS Origin - Javascript

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers to prevent any unauthorized access to resources from a different domain.

NestJS is a powerful Node.js framework that provides a built-in module for enabling CORS in your application.

Installation

To enable CORS in your NestJS application, you need to install the @nestjs/platform-express package:

npm install --save @nestjs/platform-express
Usage

To enable CORS in your application, you need to use the CorsMiddleware class from the @nestjs/platform-express package.

Here's how you can add the CorsMiddleware to your NestJS application:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { CorsMiddleware } from '@nestjs/platform-express';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.use(CorsMiddleware()); // enable CORS

  await app.listen(3000);
}
bootstrap();

You can also provide the CorsMiddleware options object to enable or configure CORS for your application. Here's how:

app.use(
  CorsMiddleware({
    origin: 'http://localhost:4200', // allow requests from this origin
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // allowed HTTP methods
    credentials: true // allow cookies to be sent across domains
  })
);
Conclusion

With NestJS and the CorsMiddleware class from the @nestjs/platform-express package, enabling CORS in your application is simple and easy. Always ensure that you only allow requests from trusted origins to prevent any unauthorized access to your resources.