Yahya
Yahya

Reputation: 746

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"]}

Upvotes: 4

Views: 5750

Answers (1)

Yahya
Yahya

Reputation: 746

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: '*/*' }));

Upvotes: 9

Related Questions