是否在一个动作上同时支持Get和Post ?



我是nestjs的新手,并试图同时在我的控制器中的方法上应用GetPost。为简单起见,我只发布了核心逻辑代码片段:

自定义修饰符

import { Get, Post } from "@nestjs/common";
import { RenderReact } from 'my-personal-package';
export function Page(path: string, view?: React.ComponentType, methodDecorators?: ((path?: string | string[]) => MethodDecorator)[]): MethodDecorator {
return (target: any, key: string, desc: PropertyDescriptor) => {
const decorators = [
Get(path), // Add Get first.
Post(path) // Add Post then.
];
if (view) {
decorators.push(RenderReact(view)); // RenderReact will return a MethodDecorator as well.
}
decorators.forEach(decorate => decorate(target, key, desc));
return desc;
};
}

控制器方法:

@Page("my-path", ThisIsMyPageFunctionalComponent, [Post]) // Post was from @nestjs/common
async return() {
// method logic
}

数组"decorators"在页面的最开始函数,

  1. 添加得到,则Post, OnlyPost作品。
  2. 添加文章,则Get, OnlyGet作品。

如何在这里同时应用Get/Post ?

正如@ michael Levi上面提到的,作为decorator factory的工作机制,我们不能以这种方式同时应用Get和Post。我已经试了很长时间了。

请参考这里的问题,就像@Kim Kern发布的

  1. 我们将公共逻辑提取到一个方法中。
  2. 将调用公共逻辑的Get方法和Post方法分开。

最新更新