在NestJs中,是否可以为单个路由启用CORS?

在NestJs中,是否可以为单个路由启用CORS?,cors,nestjs,Cors,Nestjs,我知道可以使用app.enableCors为整个应用程序启用CORS。但是可以为特定的路由启用它吗?这是一个小伪代码,但是看看nest.js文档,这应该可以工作 为应用程序启用默认cors配置: // Main app starting point import { NestFactory } from '@nestjs/core'; import { AppModule } from './AppModule'; const app = await NestFactory.create(Ap

我知道可以使用
app.enableCors
为整个应用程序启用CORS。但是可以为特定的路由启用它吗?

这是一个小伪代码,但是看看nest.js文档,这应该可以工作

为应用程序启用默认cors配置:

// Main app starting point
import { NestFactory } from '@nestjs/core';
import { AppModule } from './AppModule';

const app = await NestFactory.create(AppModule);
app.enableCors(); //Enable default cors config for the whole service 
await app.listen(3000);
然后在您想要的任何模块中(本例是主应用程序模块,但它可以是应用程序中的任何模块),为您想要的任何路由指定自定义cors配置:

// AppModule.ts
import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import cors from 'cors'; 
import { NotesController } from './NotesController';

const customNotesCorsConfig = cors({ /* your custom options here */ });

@Module({
    controllers: [NotesController]
})
export class AppModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
    consumer
        .apply(customNotesCorsConfig)
        //This one route will have its cors config overriden with the custom implementation
        .forRoutes({ path: 'notes', method: RequestMethod.POST });
    }
}
您的控制器将为不同的路由配置不同的COR:

//NotesController.ts
import { Controller, Get, Post } from '@nestjs/common';

@Controller('notes')
export class NotesController {

    // This route will use the default cors config in the app
    @Get()
    findAll(): string {
        return 'This action returns all notes';
    }

    //This route will use the custom cors config defined in the AppModule file
    @Post()
    create(): string {
        return 'This action creates a new note';
    }
}

请务必签出中间件文档,这显示了如何应用路由特定的覆盖:

感谢您的提示,我们将对此进行研究。