Search code examples
nestjs

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


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. 😃


Solution

  • 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.