Parse HTTP Requests in Express

Express·3 min read·Jan 1, 2025

In web development, parsing requests refers to the process of analyzing and converting the data contained in the message body of incoming requests into a more usable format — usually strings or JSON — that the server can understand and work with.

Parsing is usually done according to the value of the request's HTTP Content-Type header that contains a string called a media type (formerly known as MIME type) that describes the format of the message body, allowing the server to process the data sent by the client appropriately.

To do so, the Express framework provides built-in body-parsing middleware functions that allow developers to parse to parse the main 4 media types:

const { text, json, urlencoded, raw } = require('express');

Whenever used, these middlewares will try to parse the payload of the incoming request based on their Content-Type header and add a new body property to the request object (i.e. req.body).

This body property will either be defined as:

  • An object containing the parsed values.
  • An empty object in the case something went wrong, like for example a malformed message body or the use of a parsing method that doesn't match the Content-Type header.

The text middleware

The text() middleware is used to parse incoming requests whose Content-Type header is set to text/plain.

This media type is commonly used for transmitting textual data without any special formatting or structure, that doesn't require any specific processing, like ASCII characters and Unicode characters.

Example

In this example, the POST /text route uses the text() middleware to assign a string to the req.body property:

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

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.