Understanding how to retrieve the query string parameters from a GET request is crucial when building web applications with Express. The query string is the part of the URL that comes after the path and starts with a question mark “?”.
Here’s an example of a query string:
?name=flavio
Multiple query parameters can be added using “&”:
?name=flavio&age=35
So, how do you retrieve these query string values in Express?
Express simplifies this task by populating the Request.query
object automatically:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
console.log(req.query);
});
app.listen(8080);
The Request.query
object contains a property for each query parameter. If there are no query parameters, the object will be empty.
To iterate over the query parameters, you can use the for...in
loop like this:
for (const key in req.query) {
console.log(key, req.query[key]);
}
This loop will print the key and value of each query parameter.
If you need to access a specific query parameter, you can do it directly:
req.query.name; //flavio
req.query.age; //35
In conclusion, retrieving query string parameters in Express is made easy with the Request.query
object. You can iterate over all the parameters or access a specific one directly.