Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why @Body() in Post request is not working properly? [Nest.js]

Tags:

nestjs

I'm starting to learn Nest.js, so I am following an Academind Tutorial (link).

My code is not working as expected when I try to get the body variable with the @Body() decorator in the POST request. Following this part of the code in products.controller.ts

@Post()
async addProduct(@Body() body: Product) {
  console.log(body);
  const generatedId = this.productService.insertProduct(body.title, body.description, 5.99);
  return generatedId;
}

In the terminal the output is just an empty object: {}

I have searched for other examples to look at how to do it properly. I found a tutorial in DigitalOcean where they also use @Body in the POST request; they leave a the end of the tutorial a repo with the example. This example is neither working for me.

I just did a small change in addBook() function on book.service.ts file for returning the new book instead of all books

addBook(book): Promise<any> {
    return new Promise(resolve => {
        this.books.push(book);
        // resolve(this.books);
        resolve(book);
    });
}

I do the following POST request from Postman but an empty object is being the response.

POST request from Postman

All other HTTP requests are working just nice, except for the POST one.

Any ideas what could be wrong with the code? Thanks in advance. 😃

like image 463
DanielJaramillo Avatar asked Apr 07 '20 18:04

DanielJaramillo


People also ask

How to handle the POST request body in NodeJS without using framework?

How to handle the POST request body in Node.js without using a framework 1 Capturing the POSTed data. Each field in the form is delimited by the ampersand (&) character and the key and values are... 2 Parsing the data. 3 Limitations. You would have noticed that uploading a file sends only the file name to the backend and not the file... More ...

How do I get the body of a POST request?

To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String. We've then returned this name back, with a greeting message.

How to get all the body values from a POST request in nestjs?

How to get all the body values from a POST request in Nestjs? To get the body values from the POST method request, you can use the @Body () decorator function from the @nestjs/common module in Nestjs.

What is the use of @requestbody annotation?

The @RequestBody annotation allows us to retrieve the request's body. We can then return it as a String or deserialize it into a Plain Old Java Object (POJO).


2 Answers

You're sending form-data which NestJS does not correctly parse by default. You can use application/x-www-url-form-encoded or application/json along with the raw option in Postman. The JSON body would look like so:

{
  "id": "7",
  "title": "Whatever Title",
  "desscription": "whats doc",
  "author": "Me"
}

And then your server will recognize the body properly. The other option would be to add in a body parser that properly parses form-data. There are several options out there like multer, form-parser, formidable, and others.

like image 139
Jay McDoniel Avatar answered Nov 03 '22 12:11

Jay McDoniel


i also faced the same issue, first i tried to send the data as raw format but it didn't worked properly, then i used x-www-urlencoded tab on postman and it solved the issue for me.

Edit: i had a typo in raw format, now it's working fine!

like image 23
Nivethan Avatar answered Nov 03 '22 12:11

Nivethan