
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Getting Query String Variables in Express.js
In Express.js, you can directly use the req.query() method to access the string variables. As per the documentation, the req.param method only gets the route parameters, whereas the req.query method checks the query string parameters. For example, "?id=12" checks urlencoded body params.
Syntax
req.query( )
Example 1
Create a file with the name "reqQuery.js" and copy the following code snippet. After creating the file, use the command "node reqQuery.js" to run this code as shown in the example below −
// req.query() Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); var PORT = 3000; // Getting the request query string app.get('/api', function(req, res){ console.log('id: ' + req.query.id) res.send('id: ' + req.query.id); }); // Listening to the port app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
Hit the endpoint "localhost:3000/api?id=21" with a GET Request −
C:\home
ode>> node reqQuery.js Server listening on PORT 3000 id: 21
Example 2
Let's take a look at one more example.
// res.query() Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); var PORT = 3000; // Getting the request query string app.get('/api', function(req, res){ console.log('name: ' + req.query.id) res.send('name: ' + req.query.id); }); // Listening to the port app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
Hit the endpoint "localhost:3000/api?id=tutorialspoint" with a GET Request:
C:\home
ode>> node reqQuery.js Server listening on PORT 3000 name: tutorialspoint
Advertisements