NestJS如何在同一控制器Action上同时支持Get和Post请求方法
问题原因
Nest 内置的单个请求方法装饰器(Get/Post等)是@RequestMapping的语法糖,每个装饰器都会重写方法上存储的请求方法元数据,后执行的装饰器会直接覆盖前面的配置,因此始终只有最后添加的请求方法生效。
解决方案
直接使用@RequestMapping装饰器显式指定多个请求方法,配合 Nest 提供的applyDecorators工具函数组合装饰器,逻辑更稳定。
修改后的自定义装饰器代码
import { RequestMapping, RequestMethod, applyDecorators } from "@nestjs/common"; import { RenderReact } from 'my-personal-package'; import type { React } from 'react'; // 按需导入对应类型 export function Page( path: string, view?: React.ComponentType, extraMethods: RequestMethod[] = [] ): MethodDecorator { // 合并默认支持的GET/POST和额外传入的请求方法 const allowedMethods = [RequestMethod.GET, RequestMethod.POST, ...extraMethods]; const decorators = [ RequestMapping({ path: path, method: allowedMethods }) ]; if (view) { decorators.push(RenderReact(view)); } return applyDecorators(...decorators); }
控制器调用示例
如果只需要默认的GET+POST支持,不用传第三个参数即可:
@Page("my-path", ThisIsMyPageFunctionalComponent) async handleRequest() { // 方法逻辑,同时支持GET/POST请求 }
如果需要额外支持其他请求方法,直接传入对应的枚举值即可:
@Page("my-path", ThisIsMyPageFunctionalComponent, [RequestMethod.PUT]) async handleRequest() { // 方法逻辑,同时支持GET/POST/PUT请求 }
内容的提问来源于stack exchange,提问作者paul cheung
相关产品推荐
相关产品推荐

