首页 > 解决方案 > Node.js:无法读取路由中未定义的属性“密码”

问题描述

我正在尝试使用 jwt 实现我的第一个用户登录身份验证。我有一个注册端点,在那里我填充了假数据。现在我想用我在数据库中的数据登录。我正在通过 Postman 进行测试,但我有一个错误是

[Object: null prototype] {
  email: 'fakeEmail@gmail.com\t',
  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 - - 

假设这可能是因为bodyparser,我已经尝试了两种方式 //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);
    }
    });
});```

标签: node.jsexpress

解决方案


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


推荐阅读