Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

nodejs

What is Express body-parser?

Osinachi Chukwujama

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

Express body-parser is an npm library used to process data sent through an HTTP request body. It exposes four express middlewares for parsing text, JSON, url-encoded and raw data set through an HTTP request body. These middlewares are functions that process incoming requests before they reach the target controller.

body-parser doesn’t have to be installed as a separate package because it is a dependency of express version 4.16.0+. body-parser isn’t a dependency between version 4.0.0 and 4.16.0, so it will be installed separately in projects locked to those versions. body-parser middlewares will be required by express in versions of express with body-parser dependency. Versions of Express without body-parser will have to install it separately.

How to use body-parser

The middlewares that body-parser exposes can be a part of a single route or for the whole app. You will need to expose and register the required middleware.

In the code block below, the JSON parser middleware is registered for the whole application. This means all requests will pass through this middleware.

const express = require("express");
const app = express();
require("dotenv").config();

app.get("/", (req, res) => {
  res.send("<h1>Hi there, welcome to your app</h1>");
});

const jsonParser = express.json()
app.use(jsonParser);
app.post("/comment", (req, res) => {
  res.send(req.body);
});

app.listen(process.env.PORT, () =>
  console.log(`server running on port ${process.env.PORT}`)
);

Meanwhile, in the code block below, the text parser middleware is attached to a single route that returns the text it receives.

const express = require("express");
const app = express();
require("dotenv").config();

app.get("/", (req, res) => {
  res.send("<h1>Hi there, welcome to your app</h1>");
});

const textParser = express.text();

app.post("/some-route", textParser, (req, res) => {
  res.send(req.body)
});

app.listen(process.env.PORT, () =>
  console.log(`server running on port ${process.env.PORT}`)
);

Using the ‘raw’ parser middleware

The Json, url-encoded, and text parsing middlewares are used to parse their respective data types. The raw middleware is a generic middleware that expects a user-defined, request-body type.

Let’s assume we want to support yaml on our blog’s comment section, we could define an application/yml type in the POST request header and then define a yml parser using express.raw.

A POST request that is made to the /geek-comment route will only be executed if the Content-Type is set to application/yml.

const express = require("express");
const app = express();
require("dotenv").config();

app.get("/", (req, res) => {
  res.send("<h1>Hi there, welcome to your app</h1>");
});

app.use(express.json());
app.post("/comment", (req, res) => {
  res.send(req.body);
});

const ymlParser = express.raw({ type: "application/yml" });

app.post("/geek-comment", ymlParser, (req, res) => {
  console.log(req.body);
  res.send(req.body);
});

app.listen(process.env.PORT, () =>
  console.log(`server running on port ${process.env.PORT}`)
);

Conclusion

The body-parser middleware converts text sent through an HTTP request to a target format. body-parser fails to parse if the content type of the request does match that defined on the route. body-parser exposes 4 different parsers: text, JSON, URL encoded, and raw. The first three parsers can be constructed from the fourththe raw parser.

RELATED TAGS

nodejs

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring