Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express: req.params vs req.body (JSON)

Which is more correct, and why? Does it depend on the scenario? Is there a standard?

router.post("/user", function(req, res) {
  let thisUserId = req.body.userId;
});

router.post("/user/:userId", function(req, res) {
  let thisUserId = req.params.userId;
}

Thanks!

like image 661
chrisheseltine Avatar asked Feb 27 '19 10:02

chrisheseltine


Video Answer


2 Answers

This question is more about RESTful API conventions than node or express. Based on generally accepted REST conventions, this is basic CRUD operation:

/* fetch all users */
GET /users 

/* fetch specific user */
GET /users/:userId

/* create new user */
POST /users 

/* edit specific user */
PUT /users/:userId

/* delete specific user */
DELETE /users/:userId

So in your case I would say req.body is more appropriate, considering you want to create a user.

EDIT: another useful resource that supports this case: 10 best practices for better RESTful API.

like image 104
Haris Bouchlis Avatar answered Nov 15 '22 04:11

Haris Bouchlis


req.body is used to access actual form data that you 'posted'.

req.params is used for route parameters, in your case userId which is passed in the parameters:

router.post("/user/:userId", function(req, res) {
  let thisUserId = req.params.userId;
}

The official docs:

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.

Link to req.body docs

req.params

This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.

Link to req.params docs

If you want to implement guards or any other logic in your route that relies on that id (of an existing user), you pass the userID in the params.

Let's say you are submitting a form where a new user registers.. You don't want to send the credentials in the parameters since it's confidential data and easily accessible this way. Here it makes sense to put those values in the request-body and use therefore req.body..

As Haris Bouchlis already mentioned in his answer it depends on your CRUD-ops that you like to perform.

like image 41
iLuvLogix Avatar answered Nov 15 '22 06:11

iLuvLogix