Skip to content
Advertisement

node js async/await : why i can’t get the data ? req.body

i am learning about async/await at Node.js to make a restful api and I got a problem in the PUT and PATCH method, where for req.body it can’t display the data that I want

here’s the code: controllers/users

 replaceUser: async (req, res, next) => {
    //enforce that req.body must contain all the fields
    const { userId } = req.params;
    const  newUser  = req.body;
    // const result = await User.findByIdAndUpdate(userId, newUser, {new: true}).exec();
    // console.log(result)
    console.log(newUser)
    console.log(userId)

    // res.status(200).json(result);
    // console.log(userId, newUser)
},

and this code for router:

router.route('/:userId')
.get(UsersController.getUser)
.put(UsersController.replaceUser)
.patch(UsersController.updateUser)

when I enable mongoose debug, only the findone function is active, and this method works on GET and POST.

i using :

    "body-parser": "^1.18.3",
    "express": "^4.16.3",
    "express-promise-router": "^3.0.3",
    "mongoose": "^5.3.1",

i already set bodyparser middleware in my app.js.. but still won’t work for PATCH and PUT methods 🙁

please help me. I’m stuck. thank you

Advertisement

Answer

Looks like you arent corectly populating req.body with bodyParser

This is taken from the express website


req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

The following example shows how to use body-parsing middleware to populate req.body.

var app = require('express')();
var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded


replaceUser: async (req, res, next) => {
    //enforce that req.body must contain all the fields
    const { userId } = req.params;
    const  newUser  = req.body;
    // const result = await User.findByIdAndUpdate(userId, newUser, {new: true}).exec();
    // console.log(result)
    console.log(newUser)
    console.log(userId)

    // res.status(200).json(result);
    // console.log(userId, newUser)
}

Take note of:

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement