Keywords: Express | Query Parameters | Node.js | Web Development | Routing
Abstract: This article delves into how to retrieve GET query parameters in Express.js using the req.query object, covering the fundamentals of query strings, differences from route parameters, detailed code examples, and best practices. Based on Q&A data and reference articles, it explains core concepts in a step-by-step manner to help developers efficiently handle parameter access in web applications.
In web development, handling URL parameters is a common task, and Express.js, a popular Node.js framework, offers straightforward methods for accessing different types of parameters. Query parameters follow the '?' in a URL, such as in '/sample/2?color=red', where 'color=red' is the query string portion. Unlike route parameters, query parameters do not depend on path definitions and are accessed directly through a specific object.
Fundamentals of Query Strings
A query string is part of a URL used to pass key-value pairs to the server, formatted as 'key=value' with multiple parameters connected by '&'. In HTTP requests, query parameters are commonly used in GET methods for filtering, pagination, or customizing request content. Express.js automatically parses these parameters without additional processing.
Accessing Query Parameters with req.query
In Express, the req.query object parses the query string into a JavaScript object, allowing developers to access parameter values directly by property name. For example, for the URL '/sample?color=red&size=large', req.query.color returns 'red' and req.query.size returns 'large'. This approach is simple and efficient, suitable for most scenarios.
Here is a complete code example demonstrating how to set up an Express server and handle query parameters:
const express = require('express');
const app = express();
const port = 3000;
app.get('/sample', (req, res) => {
const color = req.query.color;
const size = req.query.size;
if (color && size) {
res.send(`Color: ${color}, Size: ${size}`);
} else {
res.send('Required query parameters not provided');
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});In this example, when a user visits '/sample?color=blue&size=medium', the server responds with 'Color: blue, Size: medium'. If parameters are missing, it returns a prompt. The code uses req.query to retrieve parameters directly, without defining route placeholders.
Comparison with Route Parameters
Route parameters are defined with ':' in the path, such as '/sample/:id', and accessed via req.params.id; whereas query parameters are accessed through req.query and do not rely on path structure. Route parameters are suitable for variable parts of fixed paths, while query parameters offer more flexibility for optional or dynamic data. In practice, both can be combined, e.g., in '/users/:id?role=admin', req.params.id gets the user ID and req.query.role gets the role information.
Practical Applications and Best Practices
When handling query parameters, it is advisable to validate and sanitize them to prevent security risks such as injection attacks. Express includes built-in middleware like express.urlencoded() for processing body parameters in POST requests, but for GET query parameters, req.query is sufficient. Additionally, avoid using the deprecated req.param method to ensure compatibility with the latest Express versions.
In summary, req.query is the standard way to access query parameters in Express, and when combined with route parameters, it enables the development of flexible and secure web applications. Through the examples and explanations in this article, developers can quickly master this core functionality.