Use simple parsing
An application needs standard Node-compatible query-string parsing.
Express.js · Const
The query parser application setting determines how Express parses URL query strings into req.query. It can disable parsing, select simple or extended mode, or use a custom parser.
The application setting controls how Express converts a request URL’s query string into the object exposed as req.query. It accepts false, the simple or extended parser names, or a custom function that receives the complete query string and returns an object containing query keys and values.
app.set('query parser', value)| Name | Type | Description |
|---|---|---|
value | Boolean | String | Function | Application setting value: false, "simple", "extended", or a function accepting the complete query string and returning an object. |
The configured parser determines the object available as req.query; a custom parser returns an object of query keys and values.
const express = require('express');
const app = express();
app.set('query parser', (value) => {
const result = Object.create(null);
for (const part of value.split('&')) {
const [key, raw = ''] = part.split('=');
result[decodeURIComponent(key)] = decodeURIComponent(raw.replace(/\+/g, ' '));
}
return result;
});
app.get('/search', (req, res) => {
res.json(req.query);
});
app.listen(3000);Configures a custom parser and returns parsed query parameters from /search.
An application needs standard Node-compatible query-string parsing.
An application needs nested objects or arrays represented by query parameters.
An application must apply custom decoding, validation, or parser options.
An application does not use URL query parameters.
The setting chooses how Express parses URL query strings before exposing them through req.query. It accepts false, simple, extended, or a custom function.
Follow-up: What happens when it is false? req.query is an empty object, so application code cannot obtain parsed query parameters from it.
The simple parser uses Node’s native querystring parser, while the extended parser uses qs. In Express 4, the documented default is extended.
Follow-up: When would a custom function be useful? When the application needs parsing behavior or options that the built-in choices do not provide.
Set the application value to a function. Express passes that function the complete query string, and the function must return an object mapping query keys to their values.
Follow-up: What contract must the function satisfy? It must return an object; otherwise req.query cannot represent the parsed query parameters as documented.
req.queryapp.set()querystringqs