Search code examples
javascriptjsonpostnestjshttprequest

Json request body not handled by NestJs


I've implemented a NestJs controller and then a facade service that listens to POST requests and after the request arrives, it does some operations.

Now, it works for "text/plain" content-type, but not for "application/json" content-type. The body is exactly the same.

This is the method in the controller:

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

This is the method in the facade service:

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);
    });
  }

The request in json arrives to the controller, arrives to the manageCarePlanNotification method, but does not reach the on(data) event, which is correctly reached by the text/plain request (same happens in the on (end) event).

Any help will be really appreciated! :)


Solution

  • What for inventing the wheel again?

    NestJS is there to take req/res from your back. It abstracts req/res, so first of all it is platform agnostic (Express/Fastify) and also you don't have to care about handling it and getting into troubles as you exactly did.

    When you're using Nest, you suppose to simply use @Body data: YourDataTypeInJSON and just do sth like:

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