cors - 在 NestJs 中是否可以为单个路由启用 CORS?
问题描述
我知道可以使用app.enableCors
. 但是是否可以为特定路线启用它?
解决方案
这是一个小伪代码,但查看 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
推荐阅读
- azure - Azure 上的 Flask APP 给出 import cv2 ImportError: libGL.so.1: after deployment
- javascript - 如何在不显示SVG介绍的情况下将SVG转换成Canvas?
- angular - “在'@angular/fire/firestore'中找不到导出'启用持久令牌'
- sql-server - Sql Server如何将字段的值存储在另一条记录中
- json - 无法将 []interface{} 转换为 []byte:“interface {} 是 []interface [],而不是 []uint8”
- javascript - 在标记 OpenLayers 上添加鼠标悬停事件
- java - 重构 Java 方法,使代码不会被标记为重复
- function - 无法执行 powershell 脚本。电子邮件是脚本中的函数名称。当我执行脚本时出现此错误:
- javascript - 用三元运算符反应条件渲染
- jmeter - 如何使用 timeshift 函数在 Jmeter 中以毫秒为单位生成未来时间