Open In App

Reading Query Parameters in Node

Improve
Improve
Like Article
Like
Save
Share
Report

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’.

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: Below is the code example to show the implementation of the query parameters in Nodejs:

Javascript




const express = require("express")
const path = require('path')
const app = express()
 
var 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) {
 
    var name = req.query.name
    var 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


Last Updated : 18 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads