Express req.query Property

The req.query property allows you to access the query parameters from the URL of an incoming HTTP request. Query parameters are key-value pairs included in the URL after the “?” symbol, and they are separated by “&” symbols.

Syntax:

req.query

Parameter: No parameters

Steps to Create the Application:

Step 1: Initialising the Node App using the below command:

npm init -y

Step 2: Installing the required packages:

npm i express body-parser

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2",
}

Example 1: Below is the basic example of the req.query property:

Javascript




const express = require('express');
const app = express();
const PORT = 3000;
 
app.get('/profile',
    function (req, res) {
        console.log(req.query.name);
        res.send();
    });
 
app.listen(PORT,
    function (err) {
        if (err) console.log(err);
        console.log("Server listening on PORT", PORT);
    });


Steps to run the program:

node index.js

Console Output:

Server listening on PORT 3000

Bsrowser Output: go to http://localhost:3000/profile?name=Gourav :

Server listening on PORT 3000
Gourav

Example 2: Below is the basic example of the req.query property:

Javascript




const express = require('express');
const app = express();
const PORT = 3000;
 
app.get('/user',
    function (req, res) {
        console.log("Name: ", req.query.name);
        console.log("Age:", req.query.age);
        res.send();
    });
 
app.listen(PORT,
    function (err) {
        if (err) console.log(err);
        console.log(
            "Server listening on PORT",
            PORT
        );
    });


Steps to run the program:

node index.js

Output: make a GET request to http://localhost:3000/user?name=Gourav&age=11:

Server listening on PORT 3000
Name: Gourav
Age: 11

We have a complete reference article on request methods, where we have covered all the request methods, to check those please go through Express Request Complete Reference article:



Contact Us