如何使用 `bodyParser.raw()` 获取原始体?

How to use `bodyParser.raw()` to get raw body?

我正在使用 Express 创建网络 API。 该功能是允许 API 用户向服务器发送文件。

这是我的应用设置代码:

var express = require('express');
var path = require('path');
// ...
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

// API routes
var images = require('./routes/api/img');

var app = express();

app.use(bodyParser.raw());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/api', images);

// ...

module.exports = app;

请注意我使用的是app.use(bodyParser.raw());

如何从 POST 请求中获取原始字节?

const express = require('express');
const router = express.Router();

/* POST api/img */
router.post('/img', function(req, res, next) {

  // how do I get the raw bytes?

});

module.exports = router;

解析的正文应该设置在req.body

请记住,中间件是按照您使用 app.use 设置的顺序应用的,我的理解是多次应用 bodyParser 将尝试按照该顺序解析正文,让您最后一个在 req.body 上运行的中间件的结果,即因为 bodyParser.json() 和 bodyParser.raw() 都接受任何输入,你实际上最终会尝试解析缓冲区中的所有内容进入 JSON.

如果你想发送原始数据并使用正文解析器获取你只需这样配置:

app.use(bodyParser.raw({ inflate: true, limit: '100kb', type: 'text/xml' }));

该行为不会破坏正文内容。

解析我使用的所有内容类型:

app.use(
  express.raw({
    inflate: true,
    limit: '50mb',
    type: () => true, // this matches all content types
  })
);

要在一条路线中获得原始 body:

app.put('/upload', express.raw({ inflate: true, limit: '50mb', type: () => true }), async (req, res) => {
  res.json({ bodySize: req.body.length });
});

在这种情况下,请注意先前 app.use() 的 body 解析器(例如 json)首先执行 - 因此请检查 req.body 确实是 Buffer,否则恶意调用者可能会发送类似 {"length":9999999}Content-Type: application/json 的内容。