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

99封情书 提交于 2020-05-24 04:34:24

问题


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 other examples to look 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.

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

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


回答1:


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.



来源:https://stackoverflow.com/questions/61086951/why-body-in-post-request-is-not-working-properly-nest-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!