zl程序教程

您现在的位置是:首页 >  后端

当前栏目

nodejs应用错误消息PayloadTooLarge的处理

2023-09-14 09:03:58 时间

今天使用nodejs开发时,遇到如下错误:

PayloadTooLargeError: request entity too large

根据出错信息显示的node_modules\raw-body\index.js,进入代码:

在getRawBody方法里发现一个大小检查逻辑,我传入的json长度为881790,而limit变量显示为1024:

所以触发了错误检查:

function readStream (stream, encoding, length, limit, callback) {
  var complete = false
  var sync = true

  // check the length and limit options.
  // note: we intentionally leave the stream paused,
  // so users should handle the stream themselves.
  if (limit !== null && length !== null && length > limit) {
    return done(createError(413, 'request entity too large', {
      expected: length,
      length: length,
      limit: limit,
      type: 'entity.too.large'
    }))
  }

解决方案也很简单,添加一行代码即可:

app.use(bodyParser.json({limit: ‘10mb’, extended: true}));

要获取更多Jerry的原创文章,请关注公众号"汪子熙":