In front-end and back-end development, we often encounter cross-domain problems that need to be solved. Next, we briefly introduce how to solve cross-domain problems in Nestjs.
First, install the module @nestjs/common
from the package cors
.
npm install --save @nestjs/common
Use the CORS middleware globally: In the root module of your NestJS application (usually app.module.ts
), use app.use()
the method to globally enable the CORS middleware
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CorsMiddleware } from '@nestjs/common';
@Module({
imports: [], // 导入其他模块
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(CorsMiddleware).forRoutes('*');
}
}
The method in the above code configure()
uses CorsMiddleware
the middleware and applies it to all routes. You can also limit cross-origin requests by specifying specific routes.
Custom CORS settings: If you need to customize CORS settings, you can pass a configuration object to apply()
the method and define the required options in it
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
const corsOptions: CorsOptions = {
origin: 'http://example.com', // 设置允许请求的来源
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // 设置允许的 HTTP 方法
allowedHeaders: 'Content-Type,Authorization', // 设置允许的请求头
};
// 在 configure() 方法中应用自定义的 CORS 设置
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(CorsMiddleware(corsOptions)).forRoutes('*');
}
}
In the above code, you can set origin
, methods
and allowedHeaders
to define the source of cross-domain requests, allowed HTTP methods and request headers. Through the above steps, you can implement the function of solving cross-domain problems in NestJS applications. Ensure CORS is properly configured in production environments to ensure security and data protection.