Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access raw body of a post request in Express.js?

I send this request with postman.

postman

And I console.log(req.body) returns an array like this:

{ '{"urls":["https://example.com?paramOne': 'foo',
  paramTwo: 'bar"]}' }

How can I get the whole body as a simple string like this?

{"urls":["https://example.com?paramOne=foo&paramTwo=bar"]}
like image 961
Yahya Avatar asked Oct 20 '25 05:10

Yahya


1 Answers

In app.js: Replace:

app.use(express.json());

With:

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

app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));
like image 122
Yahya Avatar answered Oct 22 '25 07:10

Yahya