【问题标题】:Nodejs bodyparse size limitNodejs bodyparser 大小限制
【发布时间】:2018-01-11 09:21:17
【问题描述】:

我使用以下代码来使用我的正文解析器:

app.use(bodyParser.urlencoded({extended:false}), bodyParser.json({limit: 1}));

基于this document, 如果我们将限制写入一个数字,它会显示正文解析器的字节数限制。我的问题是,当我通过 post 向服务器发送一个长字符串并且 JSON 字符串大于 1 个字节时,我仍然没有收到错误并且数据很容易解析。

【问题讨论】:

  • 不,你可以在 app.use() 中有多个对象参数。请在 NEO 答案中查看以下 cmets

标签: node.js limit body-parser


【解决方案1】:

请显示不起作用的代码?我相信您可能以错误的方式初始化了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);
    });
});

【讨论】:

  • 感谢 Neo 一如既往的回复!毫米不幸的是,我无法复制粘贴代码,因为它有很多依赖项,但我看到的是,如果我使用您的代码并且我使用与我编写的相同的第一个代码:app.use(bodyParser.urlencoded({extended:false}), bodyParser.json({limit: 1})); 那么它可以工作。但是,如果我从 javascript 客户端发送帖子消息并发送长字符串,它仍然不会显示任何错误
  • 您可以假设简单的客户端发布 JavaScript 代码,例如:var myObj={test:'2429384728937489293749823749'};$.post(localhost://testLink,JSON.stringify(myObj),function(data){ return data}。在这种情况下,与 myObj 对象(testLink 路由中的 req 对象)的大小无关,我不会在节点中收到错误
  • 您确定要以 json 格式发送数据吗?你能检查你的请求吗?在此处查看 ajax/jquery 的常见错误stackoverflow.com/questions/6587221/send-json-data-with-jquery
  • 好点NEO!但是,看起来我使用了正确的数据类型,但是当 json 限制为 1 字节时,长字符串类型仍然没有发生错误。我正在使用.$post(url,sendData,callback,'json'),因为它被描述为here。另一个问题是我也想独立于用户更改数据。这意味着假设您的解决方案有效(对我来说仍然无效)。然后客户端仍然可以更改客户端数据类型并向我的服务器发送很长的字符串,就像攻击一样。那我该如何预防呢?再次感谢尼奥!
  • 我的朋友,根据您链接中的 jQuery 文档,最后一个参数 dataType 指定您希望服务器响应的响应类型。不要强制执行您的请求正文类型:) 干杯。您可以在 chrome 中检查您的请求以确认。有关如何使用 jQuery 发送 json 正文的更多信息,请参阅此链接 stackoverflow.com/questions/6587221/send-json-data-with-jquery
猜你喜欢
  • 2018-06-19
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 2017-04-06
  • 2010-12-29
  • 2012-10-16
相关资源
最近更新 更多