0

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

boogeywoogy
  • 11
  • 1
  • 6

6 Answers6

1

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
Nelson Owalo
  • 2,324
  • 18
  • 37
  • still doesn't work.. data doesn't change when i tried using mongoose.debug it says "..... findOne..." but i used findByIdAndUpdate method.. it's problem? when i using my dependencies above with mongoose function? – boogeywoogy Oct 08 '18 at 13:06
  • it's just worked on POST and GET method.. PUT and PATCH not working – boogeywoogy Oct 08 '18 at 13:08
  • I am guessing that PUT and PATCH are updating the database, thus you must have a value in req.body. You probably aren't posting/populating it (via a form)? – Nelson Owalo Oct 08 '18 at 13:12
  • yaa you right, but I've filled it in the json section, in postman: body > raw > choose json/application then in the middleware i set bodyparser.json() am i wrong? – boogeywoogy Oct 08 '18 at 13:18
  • try using the `x-www-form-urlencoded` field or `form-data` in postman and enter the values there – Nelson Owalo Oct 08 '18 at 13:21
  • actually I'm following a tutorial from codeworkr in this [link](https://www.youtube.com/watch?v=1XmwszKUNR8&list=PLSpJkDDmpFZ5rZ5-Aur9WRNsBDSUS-0B9) section but I'm stuck in the sixth part when patching the data – boogeywoogy Oct 08 '18 at 13:23
  • I have seen the tutorial. You have to set the details to update, otherwise it will fail – Nelson Owalo Oct 08 '18 at 13:27
  • not yet, but as you say. I have to follow the steps appropriately (the tutorial) so that it can run well... cause im still stuck.. so maybe i manage to refactor it.. aaand many thanks sir for helping (sorry for deleting comment) xD – boogeywoogy Oct 08 '18 at 13:38
1

[SOLVED] finally I got my data from req.body.. the problem is.. I forgot checked my headers in "application/json" in postman..

im sorry guys.. take your time to help my issue :)

MBehtemam
  • 7,865
  • 15
  • 66
  • 108
boogeywoogy
  • 11
  • 1
  • 6
1

I had the same issue, and tried all the answers from stackoverflow but nothing worked. finally I found that I was sending the data in text-form which supposed to be in json. so, if you're sure that everything you doing is correct, check body section in postman and change data type to json.

0

Nodejs doesn't recognise the req.body parameters, for that to work you need to install body-parser to your project. https://www.npmjs.com/package/body-parser

there is couple of examples in the link.

0

Did you used body-parser to read the request body? If not, use below lines..

const bodyParser = require('body-parser');

app.use(bodyParser.json());

Now you can read the body by req.body

0

You can use express.json()

const app = express();
app.use(express.json());
Sanjay Singh
  • 61
  • 2
  • 4