Node JS body-parser 获取 rawBody 和 body

Node JS body-parser get rawBody and body

我目前正在以下面提到的方式实现正文解析器

 var rawBodySaver = function (req, res, buf, encoding) {
        if (buf && buf.length) {
            req.rawBody = buf.toString(encoding || 'utf8');
        }
    }
    app.use(bodyParser.urlencoded({ extended: true}))
    app.use(bodyParser.json({ verify: rawBodySaver }));
    app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
    app.use(bodyParser.raw({ verify: rawBodySaver, type: function () { return true } }));

之前,它只是 app.use(bodyParser.urlencoded({ extended: true})),我在 req.body 中得到了我的数据。

但由于一些新要求,我不得不使用 rawBody。有什么方法可以让我在 rawBodybody

中以各自的格式获取数据

目前,只有 rawBodybody 有效。两者不能一起工作。

虽然有点老套,但我喜欢你使用 verify 函数将原始数据体存储在某处的想法。我相信您的问题是由于多次调用 bodyParser.* 引起的。似乎只有最后一个调用才起作用。

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

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

app.use(bodyParser.urlencoded({
  extended: true,
  verify: rawBodySaver
}))

app.post('/', function (req, res, next) {
  console.log(`rawBody: ${req.rawBody}`)
  console.log(`parsed Body: ${JSON.stringify(req.body)}`)
  res.sendStatus(200)
})

// This is just to test the above code.
const request = require('supertest')
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, () => {})

这会打印:

rawBody: user=tobi
parsed Body: {"user":"tobi"}