Open In App

Reading Query Parameters in Node

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Node.js, query parameters are typically accessed from the URL of a GET request. When using the core HTTP module or a framework like Express, query parameters can be parsed and accessed for dynamic functionality.

A query string refers to the portion of a URL (Uniform Resource Locator) that comes after the question mark (?). Its purpose is to transmit concise data to the server directly through the URL. Typically, this data serves as a parameter for querying a database or filtering results.

The query parameter is the variable whose value is passed in the URL in the form of a key-value pair at the end of the URL after a question mark (?).

For example:

www.geeksforgeeks.org?name=abc

where ‘name‘ is the key of the query parameter whose value is ‘abc’.

Approach

To Read query parameters in Node we will be using Express.js’s req.query method. Parse the URL, extract parameters, and use them in the server-side logic for customization or filtering.

Steps to create the Application

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

npm init -y

Step 2: Installing the required packages:

npm install express ejs

Project Structure:

NodeProj

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

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

Example: This example demonstrates readign query parameters name and age from the URL, logs them to the console.

JavaScript
// Filename - index.js

const express = require("express")
const path = require('path')
const app = express()

const PORT = process.env.port || 3000

// View Engine Setup 
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")

app.get("/user", function (req, res) {

    const name = req.query.name
    const age = req.query.age

    console.log("Name :", name)
    console.log("Age :", age)
})

app.listen(PORT, function (error) {
    if (error) throw error
    console.log("Server created Successfully on PORT", PORT)
}) 

Steps to run the program:

node index.js

Output: Go to this URL “http://localhost:3000/user?name=raj&age=20” as shown below: Browser

Console Output:console output



Next Article

Similar Reads