Node.js:无法读取路由中未定义的属性“密码”

时间:2020-06-08 10:11:10

标签: node.js express

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

[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);
    }
    });
});```

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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);
      }
    });
});

我希望这会帮助遇到类似问题的人