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

你离开我真会死。 提交于 2020-01-06 07:16:31

问题


I send this request with 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"]}

回答1:


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


来源:https://stackoverflow.com/questions/50908120/how-to-access-raw-body-of-a-post-request-in-express-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!