Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

expressjs
request
query
url
communitycreator

What is req.query in Express.js?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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!

RELATED TAGS

expressjs
request
query
url
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring