Performance: req.query for query strings
This affects server-side request processing speed and how quickly query parameters are parsed and accessed.
app.get('/search', (req, res) => {
const params = req.query;
res.send(params);
});app.get('/search', (req, res) => { const query = req.url.split('?')[1]; // manual parsing of query string const params = {}; query.split('&').forEach(pair => { const [key, value] = pair.split('='); params[key] = decodeURIComponent(value); }); res.send(params); });
| Pattern | CPU Usage | Parsing Time | Code Complexity | Verdict |
|---|---|---|---|---|
| Manual query string parsing | High | Longer | Complex | [X] Bad |
| Using req.query | Low | Short | Simple | [OK] Good |
req.query represent in an Express app?req.queryreq.query holds key-value pairs from the URL query string, which comes after the question mark in a URL.req.body, headers via req.headers, and cookies via req.cookies. So, req.query is specifically for query parameters.id in Express?req.query, so to get the value of id, use req.query.id.req.params is for route parameters, req.body is for POST data, and req.headers is for HTTP headers./search?term=books&page=2?
app.get('/search', (req, res) => {
console.log(req.query.term);
console.log(req.query.page);
res.send('Done');
});term=books and page=2. These are accessible via req.query.term and req.query.page.req.query.term which is "books" and req.query.page which is "2" (strings).app.get('/items', (req, res) => {
const page = req.query.page;
if (page > 0) {
res.send(`Page number is ${page}`);
} else {
res.send('Invalid page');
}
});req.query.page is a string, e.g., "1".page to a number first.sort and limit. If limit is missing or not a positive number, it should default to 10. Which code snippet correctly implements this behavior?req.query.sort || 'asc' to default falsy/missing values to 'asc'.Number(req.query.limit) > 0 ? Number(req.query.limit) : 10 properly converts, checks positivity (>0), and defaults for missing/undefined/NaN/zero/negative.limit || 10 accepts invalid like '-1'. C: parseInt(req.query.limit) || 10 accepts negatives ('-1' is truthy). D: req.query.limit > '0' does string comparison, accepts invalid like 'a' ("a" > "0").Pass the test and this pattern moves unknown