Parsing HTTP Requests in Express.js
Express.js·4 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.
In HTTP, the Content-Type header contains a string called a media type (formerly known as MIME type), used to describe the format of the request's message body, allowing the server to process the data sent by the client appropriately.
In Express, the message body of incoming HTTP requests is not automatically parsed by the framework.
However, since version 4, Express comes pre-packaged with body-parsing middleware functions that allow developers to parse the main 4 media types, accessible through the top-level function exported by the express module:
const { text, json, urlencoded, raw } = require('express');Whenever called, 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 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-Typeheader.
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.
Unlock the Build RESTful APIs in Node.js module
Learn how to build real database-backed and framework-powered RESTful APIs with MySQL, Sequelize, and Express.
You get immediate access to:
- 37 focused lessons across MySQL, Sequelize, backend, and Express
- 4 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle