NestJs does not handle the JSON request body

After setting up a NestJs controller and a facade service for handling POST requests, I encountered an issue where the functionality only worked for content-type "text/plain" and not for "application/json", even though the body of the request was identical.

Below is the code snippet from the controller:

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

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

While the JSON request successfully reaches the controller and the manageCarePlanNotification method, it does not trigger the 'data' event as expected, unlike the text/plain request. This behavior persists in the 'end' event as well.

If anyone has any insights or suggestions on how to address this issue, it would be greatly appreciated! :)

Answer №1

Why reinvent the wheel?

NestJS simplifies handling req/res in the backend by abstracting it, making it platform agnostic (Express/Fastify) and eliminating the need for you to deal with common pitfalls.

With Nest, all you have to do is use @Body data: YourDataTypeInJSON and write something like:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to automatically insert page numbers into every internal link on an HTML page?

When in print mode, I want to display links like this: <a href="#targetPage">link</a> but I'd prefer them to appear as: <a href="#targetPage">link (page 11)</a> (assuming the target page is on page 11 in the print preview). ...

Executing an xajax/ javascript function simultaneously

Is there a way to simultaneously execute the same function? Here is an example: function convert_points() { show_loading(); xajax_ConvertPoints(); xajax_GetRegularGamingCards(); } When xajax_ConvertPoints is called, there seems to be a mill ...

Tips to swap selections in a Select2 dropdown box

Is there a way to dynamically clear a Select2 option list and reload it with new data? Despite setting the data as suggested, it seems to only append the new data without clearing the existing options. $("#optioner").select2(); $("#doit").click(functio ...

Seeking the method to obtain the response URL using XMLHttpRequest?

I'm having trouble with a page (url) that I request via XMLHttpRequest. Instead of getting a response from the requested url, the request is being directed to another page. requesting --- > page.php getting response from > directedpage.php ...

What is the best way to retrieve the value of a button using javascript?

After trying to extract the value from a button in JavaScript, here is the code I used: for(i=0; i<cars.length;i++){ var p = `<button id="myBtn" onclick="myFunction()" value="${cars[i]}">${cars[i]}</button>` func ...

What is the method for accessing HTML tag data within a script?

Looking for a way to extract a specific substring from a given string: var str = `<ul class="errorlist"><li>Enter a valid email address.</li></ul>`; Is there a method to extract the following substring? 'Enter a valid email ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

javascript utilize jquery to advance saved event

When it comes to hyperlinks, I am pausing some of my native click events to verify if the resulting page contains the desired content. After storing the jquery event object and performing some validations, my goal is to allow the event to continue as usua ...

Issue with dynamically passing select values to pop-up link in Firefox

My website has a select dropdown feature that triggers a confirmation pop up with the same selection when the user makes a choice. Upon clicking Submit, a new window opens with the corresponding link. Everything works smoothly in Safari, Chrome, and Opera ...

What is the best way to populate empty dates within an array of objects using TypeScript or JavaScript?

I am trying to populate this object with dates from today until the next 7 days. Below is my initial object: let obj = { "sessions": [{ "date": "15-05-2021" }, { "date": "16-05-2021" }, { "date": "18-05-2021" }] } The desired ...

The error message "TypeError: (0, _style.default) is not a function" occurred when using jest along with material

My current configuration looks like this: // .jestrc.json ... "moduleNameMapper": { "style$": "<rootDir>/tests/mock.ts" } // mock.ts export default {} This setup is typically used to exclude assets from jest to pre ...

Ways to verify user login through jQuery post method

I am currently working on a login test application that utilizes jQuery post and PHP. I'm encountering an issue where the application is able to read the input values but fails to send the data to server.php and consequently does not return any data. ...

Having trouble getting my Leaflet map to display even after meticulously following the quick-start guide

I am experiencing an issue where the map is not displaying at all, leaving a blank space where it should be. Despite following Leaflet's quick-start guide, I have been unable to determine the cause of this problem. Here is the code that I currently h ...

Transforming an Image URL into base64 format using Angular

I'm currently facing difficulty when attempting to convert a specified image URL into base64. In my scenario, I have a string that represents the image's path. var imgUrl = `./assets/logoEmpresas/${empresa.logoUrl}` Is there a way to directly co ...

Having trouble with ui-router: "$injector:modulerr" - it seems an error has occurred

I recently started the tutorial AngularJS Tutorial: Learn to Build Modern Web Apps with Angular and Rails by Thinkster, but encountered a problem. After creating an inline template, I ended up with a blank page and an error message $injector:modulerr with ...

You can easily dismiss the modal by clicking on any part of the screen, not just the button

I have a problem with my current code where I can only close a modal by clicking on a specific button. I want to modify it so that the modal can be closed by clicking anywhere on the screen. Unfortunately, as a JavaScript beginner, integrating new code sni ...

Is there a possible method to retrieve the Spot-Fleet-Request identification using a CloudFormation Template?

I'm facing a challenge in creating a unified template that includes the following components: 1. AWS::EC2::SpotFleet resource 2. 2 AWS::ApplicationAutoScaling::ScalingPolicy resources (for scale up and scale down) Initially, my template only had th ...

Actions cannot be performed on elements generated by ng-repeat

I am facing a challenge where I need to display a list of languages on a page, allowing users to change their selections based on previous choices. To achieve this functionality, I have written the following code snippet: ... <tbody> & ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

Displaying HTML with extracted message form URL

I have a link that redirects to this page Is there a way for me to extract the message "Message Sent Successfully" from the URL and display it in the form below? <form action="send_form_email.php" name="contactForm" method="post"> //I want to d ...