NodeJS获取请求体长度

3

我需要获取req.body中某个字段的长度。但是使用req.body.username.length <= 5时,我得到了错误提示Cannot read property 'length' of undefined。我该怎么做呢?


1
错误是关于用户名的吗?你需要确保你得到了一个用户名。所以如果你在获取req.body && req.body.username,那么首先退出登录。 - Muhammad Faizan
如果“username”是一个数组,那么它才能返回长度。 - arjun kori
4个回答

2

考虑到 JavaScript 中的对象并没有属性 length,因此您可以使用以下代码代替。

Object.keys(req.body).length

Object.keys(req.body)会返回一个所有键的数组。因此,我们可以使用.length来获取数组的长度。


这只会获取键的数量,而不是整个内容长度 - undefined

0

我曾经遇到过类似的问题。在我的Object.keys(req.body)中没有得到任何东西。后来我发现原因是我在POST请求体中发送的是原始文本而不是JSON格式。所以请确保您发送的是有效的JSON数据。


0

我相信你需要使用中间件body-parser来解析请求体,在访问其中的数据之前。

使用以下命令进行安装:

npm install body-parser

使用方法如下:

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true})); // Returns middleware that only parses urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

app.use(bodyParser.json()); // Returns middleware that only parses json. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

NPM 参考:https://www.npmjs.com/package/body-parser

我忘了提到我在函数内使用它。我可以在router.post()内使用它。错误是“无法读取未定义的属性'length'”。 - CherryBelle
1
@NoName,您能否确认req.body中是否真的包含了username - Rahul Desai
我已经找到了导致错误的原因。我的用户名是空的。 - CherryBelle

0

这个问题可能有两种可能性。

1)req.body未定义。这意味着您无法解析请求正文。要克服这个问题,请执行以下步骤。

npm install body-parser --save

在你的 app.js 文件中加入以下代码:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.set('json spaces', 1);

2. 我能想到的另一种可能是,如果您的 req.body 已经被正确解析,但在 req.body 中没有名为 username 的键。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接