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)
该行为不会破坏正文内容。
要解析我使用的所有内容类型:
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。
解析的正文应设置为req.body。
请记住,中间件按照您设置的顺序应用app.use,我的理解是,多次应用 bodyParser 将尝试按该顺序解析正文,为您留下最后一个要操作的中间件的结果req.body,即,由于 bodyParser.json() 和 bodyParser.raw() 都接受任何输入,因此您实际上最终会尝试将 Buffer 中的所有内容解析为 JSON。
| 归档时间: |
|
| 查看次数: |
11853 次 |
| 最近记录: |