How to get `GET` variables in Express.js on Node.js?
In Express.js, you can access GET (query string) variables using the req.query
object. The req.query
object contains key-value pairs of the query string parameters in a GET request. Here's an example:
const express = require('express');
const app = express();
// Define a route with a query string parameter
app.get('/example', (req, res) => {
// Access query string variables using req.query
const param1 = req.query.param1;
const param2 = req.query.param2;
// Do something with the parameters
res.send(`Received parameters: param1=${param1}, param2=${param2}`);
});
// Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
In this example:
- The route
/example
is defined to handle GET requests. - Inside the route handler function,
req.query
is used to access the query string parameters. param1
andparam2
represent the names of the query string parameters. You should replace them with the actual parameter names you expect in your application.
When a request is made to a URL like http://localhost:3000/example?param1=value1¶m2=value2
, the values of param1
and param2
will be accessible in the route handler through req.query
.
For a more dynamic approach, you can also destructure the properties directly from req.query
:
app.get('/example', (req, res) => {
const { param1, param2 } = req.query;
res.send(`Received parameters: param1=${param1}, param2=${param2}`);
});
This way, you directly extract the properties you need from req.query
into variables.
-
Comparing Node.js Testing Libraries
This guide presents a comparison of top 9 testing libraries for Node.js to help you decide which one to use in your next project
Guides -
How do I pass command line arguments to a Node.js program and receive them?
In Node.js, you can pass command line arguments to your script the same as you would for any other command line application. Simply type your arguments after the script path separated with a space ...
Questions -
Monitoring Linux with Node Exporter
This guide will teach you how to install and configure Prometheus and Node Exporter for monitoring your Linux servers
Guides
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github