110k views
4 votes
How to access the query params in express

Option 1: req.queryParameters
Option 2: req.params
Option 3: req.body
Option 4: req.query

User TRD
by
8.1k points

1 Answer

3 votes

Final answer:

In Express.js, query parameters are accessed using req.query. This object contains key-value pairs of the query parameters passed in a GET request's URL.

Step-by-step explanation:

To access the query parameters in an Express.js application, you use req.query. When a GET request is made to your server and includes query parameters (for example, /?search=books&sort=asc), you can retrieve these parameters in your route handler using req.query. This object will contain key-value pairs of the query parameters where the keys are the names of the parameters and the values are the parameters' values.

Here's a quick example:

app.get('/search', (req, res) => {
let searchTerm = req.query.search;
let sortOrder = req.query.sort;
// ... you can now use searchTerm and sortOrder variables
});

It's important to note that req.params is used for route parameters (for example, /:id), req.body is for accessing the body of a POST request, and req.queryParameters is not a standard property for accessing query parameters in Express.js.

User Ekua
by
7.9k points