Use of req.query, req.params and req.body in NODE JS

I am writing this article for beginners. Because, at the time of learning node js, this is very confusing where and how we need to use req.query, req.params and req.body .

I am going to explain these three req method below.

1.       Req.query
2.       Req.params
3.       Req.body

Req.query:
When request is coming in key and value pair, for example, if your URL looks like below URL
In the above URL, you can see that request is coming in key and value pair. First key is name and value is xyz, second key is age and value is 16.

In the node js programing, if you want to parse this url then use req.query. Below is the code snippet to parse this URL.

router.get('/search', function(req, res, next) {
  var name = req.query.name;
  console.log(`Name :  ${name}`)
  var age = req.query.age;
  console.log(`Age :  ${age}`)
  res.send('Request has parsed see console');
  });

Req.params:
When request is coming like below URL.
in the above URL, you can see the difference between first URL and this URL. In this URL value is coming without key and value pair. Key is not available. This is little bit secure then first one because user don’t know what is the meaning of xyz and 16.

To fetch these values in node js, below is the code snippet.

router.get('/search/:name/:age', function(req, res, next) {
  var name = req.params.name;
  console.log(`Name :  ${name}`)
  var age = req.params.age;
  console.log(`Age :  ${age}`)
  res.send('Request has parsed see console');
});

Req.body:
When request is coming through GUI(i.e. html or other supported views). Inside the GUI, form action should be POST.

Below is code snippet for GUI.
<form class="form-inline my-2 my-lg-0" action="/search" method="post">
      <input class="form-control mr-sm-2" type="text" name="name" placeholder="Name">
      <input class="form-control mr-sm-2" type="text" name="age" placeholder="Age">
      <button class="btn btn-outline-danger my-2 my-sm-0" type="submit">Search</button>
</form>

To fetch these value in node js, you should use req.body.name. Below is the code snippet.
router.post('/search', function(req, res, next) {
  var name = req.body.name;
  console.log(`Name :  ${name}`)
  var age = req.body.age;
  console.log(`Age :  ${age}`)
  res.send('Request has parsed see console');
});

To run this code, please ensure that body parser component has been included in your app.js. like below
var bodyParser = require('body-parser');


// body-parser middlewares
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

Thanks for reading this article. Please share this article if you found this as good.

Comments

Post a Comment

Recent Post

Recent Posts Widget

Popular posts from this blog

Capture image from webcam java code, examples

How to capture finger prints in java