Express, Request Parameters

By

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:

PropertyDescription
.appholds a reference to the Express app object
.baseUrlthe base path on which the app responds
.bodycontains the data submitted in the request body (it’s undefined until a body parser like express.json() fills it in)
.cookiescontains the cookies sent by the request (needs the cookie-parser middleware)
.hostnamethe hostname as defined in the Host HTTP header value
.ipthe client IP
.methodthe HTTP method used
.paramsthe route named parameters
.paththe URL path
.protocolthe request protocol
.queryan object containing all the query strings used in the request (read-only in Express 5)
.securetrue if the request is secure (uses HTTPS)
.signedCookiescontains the signed cookies sent by the request (needs the cookie-parser middleware)
.xhrtrue 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-parser module to process POST data. Express 5 ships express.json() and express.urlencoded() built in, so you don’t need to install anything else.

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about express: