Express - 问题解析查询参数,请求错误

Express - issue parsing query parameters, bad request

在测试我们的 Express 端点时,我们发现某些具有长查询字符串 (/?x[0]=0&x[1]=1 ... &x[100]=100) 的特定请求会失败。应用程序正在响应 HTTP 400(错误请求)。首先,我们认为查询太长,它被 firewall/nginx 阻止,或者我们遇到了某种 nodejs/express 限制。然而,经过一些实验,我们发现 /?x[21]=21 失败,而 /?x[20]=20 工作正常。这是为什么?

为什么会失败?

事实证明,默认快递设置:

  • 调用 /?x[20]=20 结果 req.query.x = [ '20' ],而
  • 调用 /?x[21]=21 结果 req.query.x = { '21': '21' }

第二个请求没有通过验证,因为我们需要一个数组而不是一个对象。

这种奇怪行为背后的原因在于 qs express 用于处理查询的库。

qs will also limit specifying indices in an array to a maximum index of 20. Any array members with an index of greater than 20 will instead be converted to an object with the index as the key

如何解决这个问题?

Qs 允许您更改 20 的限制,而 express 允许您设置自己的查询解析器。所以最简单的解决方案如下所示:

app.set('query parser', function (str) {
  return qs.parse(str, {arrayLimit: 1000});
});