【问题标题】:Does nestjs support Get and Post simultaneously on an action?Nestjs 是否支持同时在操作上获取和发布?
【发布时间】:2021-11-02 08:01:23
【问题描述】:

我是nestjs 的新手,我想同时在我的控制器中的一个方法上应用GetPost。 为简单起见,我只是贴出核心逻辑代码sn-p:

定制装饰器

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
}

Page函数最开始的数组“装饰器”,

  1. 添加Get,然后Post,只有Post有效。
  2. 添加Post,然后Get,只有Get有效。

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

【问题讨论】:

  • 我认为由于 HTTP 装饰器工厂的工作方式,您不能这样做。 Here 你可以看到只有最后一个元数据附加到目标方法。也许有办法做到这一点,但不使用 GetPost

标签: node.js reactjs frontend nestjs web-frontend


【解决方案1】:

正如@Micael Levi 上面提到的,作为装饰器工厂如何工作的机制,我们不能以这种方式同时应用 Get 和 Post。我已经尝试了很长时间。

请参考问题here,如@Kim Kern 所发

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

【讨论】:

    猜你喜欢
    • 2019-05-17
    • 2011-06-29
    • 1970-01-01
    • 2023-04-09
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多