/

How to Retrieve the GET Query String Parameters using Express

How to Retrieve the GET Query String Parameters using Express

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:

1
?name=flavio

Multiple query parameters can be added using “&”:

1
?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:

1
2
3
4
5
6
7
8
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:

1
2
3
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:

1
2
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.

tags: [“Express”, “GET request”, “query string parameters”]