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

Bel*_*014 8 node.js express body-parser

我正在使用创建Web API Express.该功能允许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;
Run Code Online (Sandbox Code Playgroud)

请注意我正在使用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;
Run Code Online (Sandbox Code Playgroud)

小智 9

如果您想发送原始数据并使用正文解析器获取,您只需以这种方式配置:

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

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

  • 重要的是添加**type**参数。如果 **type** 被省略,默认行为是检查类型“application/octet-stream”,如在 [here](https://github.com/expressjs/body-parser/blob/bd386d3a7d540bac90bbdaff88f653414f6647fc/ lib/types/raw.js#L39)(对于该库的大多数用户来说可能是意料之外的)。要匹配任何内容类型,请使用 `type: "*/*"`。 (3认同)

Mor*_*itz 8

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

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

只需通过一条路线即可获取原始主体:

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

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


Squ*_*rel 4

解析的正文应设置为req.body

请记住,中间件按照您设置的顺序应用app.use,我的理解是,多次应用 bodyParser 将尝试按该顺序解析正文,为您留下最后一个要操作的中间件的结果req.body,即,由于 bodyParser.json() 和 bodyParser.raw() 都接受任何输入,因此您实际上最终会尝试将 Buffer 中的所有内容解析为 JSON。

  • 很好的问题,显然是有的!来自文档[1](https://www.npmjs.com/package/body-parser#bodyparserrawoptions) raw 函数采用可能包含以下任意键的选项选项对象: type 选项用于确定什么中间件将解析的媒体类型。这个选项可以是一个函数或一个字符串...它甚至接受 mime 类型的通配符,因此这应该可以让您获得所需的粒度。 (2认同)