我需要获取req.body中某个字段的长度。但是使用req.body.username.length <= 5
时,我得到了错误提示Cannot read property 'length' of undefined
。我该怎么做呢?
我需要获取req.body中某个字段的长度。但是使用req.body.username.length <= 5
时,我得到了错误提示Cannot read property 'length' of undefined
。我该怎么做呢?
考虑到 JavaScript 中的对象并没有属性 length
,因此您可以使用以下代码代替。
Object.keys(req.body).length
Object.keys(req.body)
会返回一个所有键的数组。因此,我们可以使用.length
来获取数组的长度。
我曾经遇到过类似的问题。在我的Object.keys(req.body)中没有得到任何东西。后来我发现原因是我在POST请求体中发送的是原始文本而不是JSON格式。所以请确保您发送的是有效的JSON数据。
我相信你需要使用中间件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.
req.body
中是否真的包含了username
? - Rahul Desai这个问题可能有两种可能性。
1)req.body未定义。这意味着您无法解析请求正文。要克服这个问题,请执行以下步骤。
npm install body-parser --save
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 的键。