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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With