I am making an express application that handles post data. Because the request body could be any content type and/or binary, I would like req.body
to be a Buffer
. So what should I use to get a Buffer
that represents the request body? Here is my code:
JavaScript
x
8
1
import express from "express";
2
3
const app = express();
4
app.get("/", (req, res) => {
5
// Get request body as buffer
6
// Do something with the buffer
7
});
8
Advertisement
Answer
body-parser can help achieve this, code example would be as,
JavaScript
1
13
13
1
import express from 'express';
2
const bodyParser = require('body-parser');
3
const app = express();
4
const options = {
5
type: 'application/octet-stream',
6
};
7
app.use(bodyParser.raw(options));
8
9
app.get('/', (req, res) => {
10
const bufferObject = req.body; // Get request body as buffer
11
// Do something with the buffer
12
});
13
See more details about Raw body parser and default options needs to be supplied – bodyParser.raw([options])