给出 "Cannot read property 'password' of undefined" 而不是处理错误

Giving "Cannot read property 'password' of undefined" instead of handling the error

我正在尝试使用 express js 和 dynamodb 构建用户登录系统,但问题是每当我尝试使用正确的电子邮件或密码登录用户时,它工作正常,但如果我正在使用任何错误的电子邮件,它都无法处理错误。它给了我一些错误,比如找不到未定义的密码。 有人可以告诉我如何处理这个错误以及为什么会出现这个错误吗? 我尝试了一些类似于我的 ,但实际上并没有解决问题。 提前致谢。

这是我的整个 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;

这是我遇到的错误:

I:\somePath\node_modules\aws-sdk\lib\request.js:31
            throw err;
            ^

Error [TypeError]: Cannot read property 'password' of undefined

当数据不是 return 有效数据时,您需要添加一些内容来捕获。如果您能 post 数据对象的外观,那将会有所帮助。

(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");
    }
  }
}