我使用以下代码来使用我的身体解析器:
app.use(bodyParser.urlencoded({extended:false}), bodyParser.json({limit: 1}));
基于this document, 如果我们将限制写入一个数字,它会显示正文解析器的字节数限制。我的问题是,当我通过post发送一个长字符串到服务器并且JSON字符串仍然大于1字节时,我没有得到任何错误,并且数据很容易解析。
答案 0 :(得分:0)
请显示无效的代码?我相信您可能已经错误地初始化body-parser
或者存在其他问题。
例如,下面的代码测试limit
,它通过返回http代码413来工作。
const express = require('express');
const bodyParser = require('body-parser');
const rp = require('request-promise');
const request = require('request');
const app = express();
// change this to 1MB and the test will pass
app.use(bodyParser.json({ limit: '1b' }));
app.post('/', function (req, res) {
res.send('done');
});
//wait for a connection
app.listen(3000, async () => {
console.log('Server started.');
const options = {
url: 'http://localhost:3000/',
method: 'post',
json: true,
body: {
test: '1234567890'
},
resolveWithFullResponse: true
};
rp(options).catch((err) => {
console.log(err);
});
});