How to Extract Request Body in Express JS

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

Express.js is a fast, unopinionated, minimalist web framework for Node.js, which is used extensively to build back-end services or APIs. One of the fundamental tasks when processing HTTP requests is to extract the request body. The request body is where data sent by the client is stored, often as JSON, form data, or URL encoded data. To be able to work with this data in Express, one has to use middleware that parses the body of an incoming request before handlers have access to it. This tutorial will guide you on how to extract the request body in Express.js, demonstrating multiple approaches with code examples.

Basic Body Parsing with Express

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

// Parse JSON bodies
app.use(express.json());

app.post('/data', (req, res) => {
    const requestBody = req.body;
    console.log(requestBody);
    res.status(200).send('Data Received');
});

app.listen(3000, () => console.log('Server running on port 3000'));

Here we are using express.json(), a built-in middleware in Express.js that parses incoming requests with JSON payloads. This is the simplest form of body parsing and is suitable for content-type of application/json.

Handling URL Encoded Data

app.use(express.urlencoded({ extended: true }));

app.post('/form', (req, res) => {
    const formData = req.body;
    console.log(formData);
    res.status(200).send('Form Data Received');
});

The express.urlencoded() middleware is used to parse bodies from URL encoded data. The extended: true option allows for rich objects and arrays to be encoded into the URL encoded format, allowing for a JSON-like experience with URL encoded.

Handling Multiform Data

To handle multipart/form-data, which is primarily used for uploading files, we need a different kind of middleware because Express does not have a built-in one for this purpose.

const multer = require('multer');
const upload = multer();

app.post('/upload', upload.single('file'), (req, res) => {
    const fileData = req.file;
    console.log(fileData);
    res.status(200.send('File Uploaded'));
});

In this code snippet, we’re using Multer, a Node.js middleware for handling multipart/form-data. We are particularly calling upload.single('file') for single file upload which injects the file data into req.file.

Advanced Parsing with Custom Middleware

At times, you might need to perform custom parsing, either because you have complex requirements, or you’re dealing with a non-standard content type.

const rawBodyBuffer = (req, res, buf, encoding) => {
    if (buf && buf.length) {
        req.rawBody = buf.toString(encoding || 'utf8');
    }
};

app.use(express.json({ verify: rawBodyBuffer }));

app.post('/custom', (req, res) => {
    console.log(req.rawBody);
    res.status(200).send('Custom Data Received');
});

By providing a custom function to the verify option of the JSON body parser, you can access the raw body of the request.

Conclusion

In this tutorial, we’ve covered several methods to extract request bodies in Express.js. Using built-in middleware like express.json() and express.urlencoded() you can handle most common use cases. For multipart data, Multer is a reliable option. And for more complex scenarios, custom middleware can give you the flexibility you need. Always ensure that you’re parsing the body data securely and efficiently to keep your applications healthy and robust.