[英]Giving "Cannot read property 'password' of undefined" instead of handling the error
I'm trying to build a user login system using express js and dynamodb, but the issue is whenever I'm trying to login a user using correct email or password, it works fine, but if I'm using any wrong email, it's not able to handle the error.我正在尝试使用 express js 和 dynamodb 构建用户登录系统,但问题是每当我尝试使用正确的 email 或密码登录用户时,它工作正常,但如果我使用任何错误的 email,它就是无法处理错误。 It's giving me some error like cannot find password of undefined.它给了我一些错误,例如找不到未定义的密码。 Can someone please tell me how to handle with this error and why this error?有人可以告诉我如何处理此错误以及为什么会出现此错误吗? I tried some stackoverflow question similar to mine, but that actually does not solve the problem.我尝试了一些类似于我的stackoverflow问题,但这实际上并没有解决问题。 Thanks in advance.提前致谢。
This is my whole userLogin
file:这是我的整个userLogin
文件:
const AWS = require("aws-sdk"); const express = require("express"); const bcrypt = require("bcrypt"); const jwt = require("jsonwebtoken"); require("dotenv").config(); AWS.config.update({ region: "us-east-2" }); const docClient = new AWS.DynamoDB.DocumentClient(); const router = express.Router(); router.post("/login", (req, res, next) => { user_type = "employee"; const email = req.body.email; docClient.get( { TableName: "users", Key: { user_type, email, }, }, (err, data) => { if (err) { res.send("Invalid username or password"); } else { if (data && bcrypt.compareSync(req.body.password, data.Item.password)) { const token = jwt.sign( { email: data.Item.email, }, process.env.SECRET, { expiresIn: "1d" } ); res.status(200).send({ user: data.Item.email, token: token }); next(); } else { res.status(400).send("Password is wrong"); } } } ); }); module.exports = router;
And this is the error I'm getting:这是我得到的错误:
I:\somePath\node_modules\aws-sdk\lib\request.js:31 throw err; ^ Error [TypeError]: Cannot read property 'password' of undefined
You need to add something to catch when data doesn't return valid data.当数据没有返回有效数据时,您需要添加一些东西来捕获。 If you could post what the data object looks like, that would help.如果您可以发布数据 object 的样子,那将有所帮助。
(err, data) => {
if (err) {
res.send("Invalid username or password");
} else {
// Add data.Item check
if (data && data.Item && bcrypt.compareSync(req.body.password, data.Item.password)) {
const token = jwt.sign({
email: data.Item.email,
},
process.env.SECRET, {
expiresIn: "1d"
}
);
res.status(200).send({
user: data.Item.email,
token: token
});
next();
} else {
res.status(400).send("Password is wrong");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.