Skip to content
Advertisement

Get buffer from post body in Expressjs

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:

import express from "express";

const app = express();
app.get("/", (req, res) => {
  // Get request body as buffer
  // Do something with the buffer
});

Advertisement

Answer

body-parser can help achieve this, code example would be as,

import express from 'express';
const bodyParser = require('body-parser');
const app = express();
const options = {
  type: 'application/octet-stream',
};
app.use(bodyParser.raw(options));

app.get('/', (req, res) => {
  const bufferObject = req.body; // Get request body as buffer
  // Do something with the buffer
}); 

See more details about Raw body parser and default options needs to be supplied – bodyParser.raw([options])

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement