Express, Request Parameters
By Flavio Copes
Find the Express request property you need: route parameters, URL queries, parsed request bodies, cookies, headers, and connection information.
Request parameters
The Express Request object holds the information sent by the client. Use req.params for named route segments, req.query for URL query parameters, and req.body for a parsed request body.
These are the main properties you’ll likely use:
| Property | Description |
|---|---|
| .app | holds a reference to the Express app object |
| .baseUrl | the base path on which the app responds |
| .body | contains the data submitted in the request body (it’s undefined until a body parser like express.json() fills it in) |
| .cookies | contains the cookies sent by the request (needs the cookie-parser middleware) |
| .hostname | the hostname as defined in the Host HTTP header value |
| .ip | the client IP |
| .method | the HTTP method used |
| .params | the route named parameters |
| .path | the URL path |
| .protocol | the request protocol |
| .query | an object containing all the query strings used in the request (read-only in Express 5) |
| .secure | true if the request is secure (uses HTTPS) |
| .signedCookies | contains the signed cookies sent by the request (needs the cookie-parser middleware) |
| .xhr | true if the request is an XMLHttpRequest |
URL query parameters
For a URL such as /search?name=flavio, read req.query.name. Query parameters can appear on a GET, POST, or any other request method.
See how to read query string parameters in Express for repeated keys, nested values, and Express 5’s parser behavior.
Parsed request bodies
Clients can send data in the request body, for example when submitting forms or posting JSON. Body data is separate from the query string in the URL.
How can you access this data?
If the data was sent as JSON, using Content-Type: application/json, you will use the express.json() middleware:
const express = require('express')
const app = express()
app.use(express.json())
If the data was sent using Content-Type: application/x-www-form-urlencoded, you will need to use the express.urlencoded() middleware:
const express = require('express')
const app = express()
app.use(express.urlencoded({
extended: true
}))
In both cases you can access the data by referencing it from Request.body:
app.post('/form', (req, res) => {
const name = req.body.name
})
If the body wasn’t parsed, because no parser is set up or the request’s Content-Type doesn’t match it, req.body is undefined in Express 5. In Express 4 the built-in parsers set it to an empty object {} instead. So check it before reading properties from it, or req.body.name throws a TypeError.
Note: very old Express versions required the separate
body-parsermodule to process POST data. Express 5 shipsexpress.json()andexpress.urlencoded()built in, so you don’t need to install anything else.
Want me to talk about your product? You can sponsor this site.