【问题标题】:Json request body not handled by NestJsNestJs 未处理 Json 请求正文
【发布时间】:2021-11-11 06:23:10
【问题描述】:

我已经实现了一个 NestJs 控制器,然后是一个外观服务,它监听 POST 请求,在请求到达后,它会执行一些操作。

现在,它适用于“text/plain”内容类型,但不适用于“application/json”内容类型。 身体完全一样。

这是控制器中的方法:

  @Public()
  @Post(SERVER_COVID_A_CASA_CARE_PLAN_NOTIFICATION_PATH)
  getNotification(@Req() request: Request, @Res() response: Response) {
    this.facade.manageCarePlanNotification(request, response);
  }

这是门面服务中的方法:

manageCarePlanNotification(request: Request, response: Response) {
    let jsonBodyReq = '';

    request.on('data', function (data) {
      jsonBodyReq += data;
    });

    request.on('end', () => {
      this.manageCarePlanNotificationRequest(jsonBodyReq, response);
    });

    request.on('error', function (e) {
      console.log(e.message);
    });
  }

json 中的请求到达控制器,到达 manageCarePlanNotification 方法,但没有到达 on(data) 事件,这由 text/plain 请求正确到达(同样发生在 on(end) 事件中) .

任何帮助将不胜感激! :) 谢谢

【问题讨论】:

    标签: json api post httprequest nestjs


    【解决方案1】:

    又要发明什么轮子?

    NestJS 可以从您的背后获取 req/res。它抽象了 req/res,因此首先它与平台无关(Express/Fastify),而且您不必像以前那样关心处理它并遇到麻烦。

    当您使用 Nest 时,您假设只需使用 @Body data: YourDataTypeInJSON 并执行以下操作:

      @Public()
      @Post(SERVER_COVID_A_CASA_CARE_PLAN_NOTIFICATION_PATH)
      getNotification(@Body() data: IDontKnowYourDataType) {
        return this.facade.manageCarePlanNotificationRequest(data);
      }
    

    【讨论】:

    • 谢谢,不幸的是我正在自学 NestJs,我在各种教程中发现了这个逻辑,所以你现在可以使用 json。
    • 我很高兴它对你有用!
    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 2023-03-07
    • 1970-01-01
    • 2020-10-25
    相关资源
    最近更新 更多