Node.js:无法读取路由中未定义的属性'password'



我正在尝试使用 jwt 实现我的第一个用户登录身份验证。我有一个注册终结点,我在其中填充了虚假数据。现在我想使用数据库中的数据登录。我正在通过邮递员进行测试,但我有一个错误,即

[Object: null prototype] {
email: 'fakeEmail@gmail.comt',
password: '12345678'
}
(node:14781) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'password' of undefined
at /home/me/coding/project/backend/routes/user.js:38:40
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:14781) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14781) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
POST /user/login - - ms - - 

假设这可能是因为身体解析器,我已经尝试了两种方式 //app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser());但同样的错误。 这是我的登录端点

router.post("/login",(req, res) => {
const {email, password } = req.body; 
console.log(req.body)
pool
.query("SELECT * FROM users WHERE email = $1 AND password = $2 LIMIT 1", [email, password ])
.then(res => {
const data =  res.rows[0];
if ( email  && password === data.password) {
const token = jwt.sign({ email: req.body.email }, "mySecretKey", {
expiresIn: "30 day",
});
res.send(token);
} else {
res.sendStatus(401);
}
});
});```

您在res对象中遇到问题,请尝试登录 res 然后阻止。 res.rows[0] 似乎未定义

我的问题是,我有注册端点,我正在使用Bcrypt,我必须在登录端点中验证。因此,我遇到了错误。 所以,这是我更正的登录端点

router.post("/login", (req, res) => {
const { email, password } = req.body;
pool
.query("SELECT * FROM users WHERE email = $1 LIMIT 1", [email])
.then((result) => {
const data = result.rows[0];
if (result.rows.length > 0 && email) {
bcrypt.compare(password, data.password, function (err, result) {
if (result) {
const token = jwt.sign({ email: req.body.email }, "mySecretKey", {
expiresIn: "30 days",
});
res.send(token);
} else {
res.sendStatus(401);
}
});
} else {
res.sendStatus(401);
}
});
});

我希望,它会帮助有类似问题的人

最新更新