What is req.query in Express.js?

req.query is a request object that is populated by request query strings that are found in a URL. These query strings are in key-value form. They start after the question mark? in any URL. And if there are more than one, they are separated with the ampersand&. See example below.

Example

https://educative.io/user?name=Theodore&isAuthor=true

From the above code, the query strings are name and isAuthor. When this request is made, the req.query object becomes populated with the query strings.

req.query = {name: "Theodore", isAuthor: true}

How to use expressJs

  1. Create an application and start the server.
var express = require('express');
var app = express();
const PORT = 3000;
app.listen(PORT, ()=>{
console.log("app running on port "+PORT);
})
  1. Set up the route for our request.
app.get("/user", (req, res)=>{
var name = req.query.name;
var isAuthor = req.query.isAuthor;
res.json({
name,isAuthor
})
})
  1. Open your browser and request the route /user?name=Theodore&isAuthor=true".
    This will return a JSON object with the following result.
{
   "name": "Theodore",
   "isAuthor": "true"
}

Thanks for reading!

Free Resources