Getting the Request Body in Express

Oct 22, 2019

Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4.16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.

JSON Request Body

Express has a built-in express.json() function that returns an Express middleware function that parses JSON HTTP request bodies into JavaScript objects. The json() middleware adds a body property to the Express request req. To access the parsed request body, use req.body as shown below.

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

// Parse JSON bodies for this app. Make sure you put
// `app.use(express.json())` **before** your route handlers!
app.use(express.json());

app.post('*', (req, res) => {
  req.body; // JavaScript object containing the parse JSON
  res.json(req.body);
});
const server = await app.listen(3000);

// Demo showing the server in action
const axios = require('axios');
const res = await axios.post('http://localhost:3000/', {
  answer: 42
});
res.data; // `{ answer: 42 }`

Common Gotchas

If the JSON body is malformed, Express will error out with an HTTP 400. This error also triggers error handling middleware.

const express = require('express');
const app = express();
app.use(express.json());
app.post('*', (req, res) => {
  res.json(req.body);
});

// Add error handling middleware that Express will call
// in the event of malformed JSON.
app.use(function(err, req, res, next) {
  // 'SyntaxError: Unexpected token n in JSON at position 0'
  err.message;
  next(err);
});
const server = await app.listen(3000);

// Demonstrate the server in action
const axios = require('axios');
const headers = { 'Content-Type': 'application/json' };
const err = await axios.
  post('http://localhost:3000/', 'not json', { headers }).
  then(() => null, err => err);

// Express will send an HTTP 400 by default if JSON middleware
// failed to parse.
err.response.status; // 400
err.message; // 'Request failed with status code 400'

It is important to note that, by default, the json() middleware ignores any request whose Content-Type header isn't something that Express recognizes as JSON. If express.json() is silently ignoring your request, make sure you check the Content-Type header.

const express = require('express');
const app = express();
app.use(express.json());
app.post('*', (req, res) => {
  // undefined, body parser ignored this request
  // because of the content-type header
  req.body;
  res.json(req.body);
});
const server = await app.listen(3000);

// Demo of making a request the JSON body parser ignores.
const axios = require('axios');
const headers = { 'Content-Type': 'text/plain' };
const res = await axios.
  post('http://localhost:3000/', 'not json', { headers });

res.data; // Empty object `{}`

URL-Encoded Form Body Parser

Express has an officially supported module body-parser that includes a parser for URL-encoded request bodies, like the ones submitted by HTML forms.

const express = require('express');
const app = express();
app.use(require('body-parser').urlencoded({ extended: false }));
app.post('*', (req, res) => {
  req.body; // { answer: 42 }
  res.json(req.body);
});
const server = await app.listen(3000);

// Demo of making a request with a URL-encoded body.
const axios = require('axios');
const headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
};
const res = await axios.
  post('http://localhost:3000/', 'answer=42', { headers });

res.data; // { answer: 42 }

Files

Neither Express nor body-parser supports file uploads out of the box. However, you can use the Formidable module on npm to handle file uploads. You can learn how on our tutorial on file uploads with Express.


More Express Tutorials