首页 > 解决方案 > 在 NestJs 中是否可以为单个路由启用 CORS?

问题描述

我知道可以使用app.enableCors. 但是是否可以为特定路线启用它?

标签: corsnestjs

解决方案


这是一个小伪代码,但查看 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 });
    }
}

您的控制器将为不同的路由配置不同的 cors:

//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';
    }
}

请务必查看中间件文档,这显示了如何应用特定于路由的覆盖:https ://docs.nestjs.com/middleware


推荐阅读