Categories
Express JavaScript Answers

How to Get Raw Request Body with Express?

Spread the love

To get raw request body in our Express app, we can add the raw body parsing function and set that as the value of the verify option of the middleware.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser');

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

const options = {
  verify: rawBodySaver
};

app.use(bodyParser.json(options));

app.post('/', (req, res) => {
  console.log(req.rawBody)
  res.send('hello world')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We have the rawBodySaver function that gets the buf parameter, which has the raw request body buffer.

Then we call toString on it with the encoding and assign that to the req.rawBody property.

Next, we set the verify property of options to rawBodySaver and then use options as the argument for bodyParser.json to set rawBodySaver as the function to run when the request body is being parsed.

Then in the POST / route, we can get the raw request body from the req.rawBody property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *