Request Parameters in Express

Jul 16, 2019

The first parameter to Express route handlers and middleware functions is the Express request object. This parameter is usually called req.

const express = require('express');
const app = express();

app.get('*', function(req, res) {
  // `req` is an instance of Node.js' built-in HTTP request class,
  // with some additional features from Express
  req instanceof require('http').IncomingMessage; // true

  res.json({ ok: 1 });
});

const server = await app.listen(3000);

Request Parameters

Express parses query string parameters by default, and puts them into the req.query property.

const axios = require('axios');
const express = require('express');
const app = express();

app.get('*', function(req, res) {
  const name = req.query.name; // 'Jean-Luc Picard'
  const rank = req.query.rank; // 'Captain'
  res.json({ name, rank });
});

const server = await app.listen(3000);

// Send a GET request to the server with URL-encoded params in the
// query string
const querystring = 'name=Jean-Luc Picard&rank=Captain';
const res = await axios.get('http://localhost:3000?' + querystring);

res.data.name; // 'Jean-Luc Picard'
res.data.rank; // 'Captain'

Express also supports named route parameters and puts them in the req.params object. Named route parameters are always strings, and Express automatically decodes them using decodeUriComponent().

const axios = require('axios');
const express = require('express');
const app = express();

app.get('/:model/:id', function(req, res) {
  const model = req.params.model; // 'user'
  const id = req.params.id; // '1'
  res.json({ model, id });
});

const server = await app.listen(3000);

// Send a GET request to the server with URL params
const res = await axios.get('http://localhost:3000/user/1');

res.data.model; // 'user'
res.data.id; // '1'

Express does not parse the request body for you by default. To opt in to parsing JSON request bodies, use the express.json() middleware. Express will then parse the HTTP request body and put the parsed body in req.body.

const axios = require('axios');
const express = require('express');
const app = express();

// Parse the request body as JSON. Requires Express >= 4.16.0.
app.use(express.json());

app.put('*', function(req, res) {
  const name = req.body.name; // 'Jean-Luc Picard'
  const rank = req.body.rank; // 'Captain'
  res.json({ name, rank });
});

const server = await app.listen(3000);

// Send a PUT request to the server with a request body
const body = { name: 'Jean-Luc Picard', rank: 'Captain' };
const res = await axios.put('http://localhost:3000', body);

res.data.name; // 'Jean-Luc Picard'
res.data.rank; // 'Captain'

Headers

To get the value of an HTTP request header, you should use Express' req.get() function. You may also use Node.js' native req.headers property.

const axios = require('axios');
const express = require('express');
const app = express();

app.get('*', function(req, res) {
  // `req.get()` is case-insensitive.
  const authorization = req.get('authorization');

  // Or you can use `req.headers`
  req.headers.authorization;

  res.json({ authorization });
});

const server = await app.listen(3000);

// Send a GET request to the server with an 'Authorization' header
const res = await axios.get('http://localhost:3000', {
  headers: {
    'Authorization': 'test'
  }
});

res.data.authorization; // 'test'

Here's a tutorial on how to set request headers in Axios if you're unfamiliar with Axios.

Body Size Limit

By default, express.json() limits the request body to 100kb. If the request body is any larger, Express will throw an HTTP 413 "Payload Too Large" error. You can configure this limit using the limit option to express.json().

const axios = require('axios');
const express = require('express');
const app = express();

// Set the body size limit to 10 bytes
app.use(express.json({ limit: 10 }));

app.put('*', function(req, res) {
  const name = req.body.name; // 'Jean-Luc Picard'
  const rank = req.body.rank; // 'Captain'
  res.json({ name, rank });
});

const server = await app.listen(3000);

// Send a PUT request to the server with a request body
const body = { name: 'Jean-Luc Picard', rank: 'Captain' };
const err = await axios.put('http://localhost:3000', body).
  catch(err => err);

err.response.status; // 413

Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials