Reading Query Parameters in Node.js
The query parameter is the variable whose value is passed in the URL in the form of 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 query parameter whose value is ‘abc’.
We just create a folder and add a file as index.js. To run this file you need to run the following command.
node index.js
Filename: index.js
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:
- The project structure will look like this:
- Make sure you have installed ‘view engine’ like I have used ‘ejs’ and install express module using the following commands:
npm install express npm install ejs
- Run index.js file using below command:
node index.js
- Open browser and type this URL “http://localhost:3000/user?name=raj&age=20” as shown below:
- Go back to console and you can see the Query parameters key, value as shown below:
So this is how you can read Query parameters in Node.js.
Please Login to comment...