最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

从对象数组访问值返回未定义

IT培训 admin 4浏览 0评论

从对象数组访问值返回未定义

[我试图在nodejs中将用户信息作为api结果发送。成功登录后,我将获得此数据。因为我必须通过令牌发送角色和用户名。

[ { _id: 5d9db3d9eb2e7c7708b2787a,
   username: 'akasthee',
   password: '12345',
   role: 'User',
   __v: 0 } ]
users.find({
        username: req.body.username, password: req.body.password
    }, (err, user) => { if (user.length == 1) {
            var token = jwt.sign({ userID: user._id, username: req.body.username }, 'user_authenticate', { expiresIn: '10d' });

            res.status(200).send({ token:token ,role : user.role});
        }});

但是user.role返回未定义我尝试了user.filter,但返回的是未定义的

回答如下:

您正在检查长度if (user.length == 1),因此它应该是数组,然后代码行应该是]

res.status(200).send({ token:token ,role : user[0].role});

从对象数组访问值返回未定义

[我试图在nodejs中将用户信息作为api结果发送。成功登录后,我将获得此数据。因为我必须通过令牌发送角色和用户名。

[ { _id: 5d9db3d9eb2e7c7708b2787a,
   username: 'akasthee',
   password: '12345',
   role: 'User',
   __v: 0 } ]
users.find({
        username: req.body.username, password: req.body.password
    }, (err, user) => { if (user.length == 1) {
            var token = jwt.sign({ userID: user._id, username: req.body.username }, 'user_authenticate', { expiresIn: '10d' });

            res.status(200).send({ token:token ,role : user.role});
        }});

但是user.role返回未定义我尝试了user.filter,但返回的是未定义的

回答如下:

您正在检查长度if (user.length == 1),因此它应该是数组,然后代码行应该是]

res.status(200).send({ token:token ,role : user[0].role});

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论