Home > Back-end >  Can't get data from req.body but get data from req.params
Can't get data from req.body but get data from req.params

Time:08-05

I have a code like this (pic 1). I want to get user data. But the problem is that I don't get anything in req.body (undefined), although in req.params I get what I need. Who can suggest what to do?

console.log(req);
if (req.body.password) {
  req.body.password = CryptoJS.AES.encrypt(
    req.body.password,
    process.env.PASS_SEC
  ).toString();
}

try {
  const updatedUser = await User.findByIdAndUpdate(
    req.params.id,
    {
      $set: req.body,
    },
    { new: true }
  );

  res.status(200).json(updatedUser);
} catch (err) {
  res.status(500).json(err);
}
})```


**Here is my request in Insomnia: **

https://imgur.com/a/JiCXaDe

CodePudding user response:

Try doing:

npm i body-parser

// then in your app
var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// create application/json parser
var jsonParser = bodyParser.json()


// POST /api/users gets JSON bodies
app.put('/api/users', jsonParser, function (req, res) {
  console.log(req.body);
})

CodePudding user response:

I can get data from POST request, but from PUT - no.

enter image description here

  • Related