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 | const express = require('express'); |
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 | for (const key in req.query) { |
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 | req.query.name; //flavio |
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”]