【问题标题】:UnhandledPromiseRejectionWarning: undefined in MongooseUnhandledPromiseRejectionWarning:在猫鼬中未定义
【发布时间】:2019-03-02 14:24:40
【问题描述】:

尝试使用 Mongoose 对用户进行身份验证时,我在控制台中收到以下警告:

(node:20114) UnhandledPromiseRejectionWarning: undefined (node:20114) 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(). (rejection id: 1) (node:20114) [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.

尝试跟踪堆栈不会产生任何结果,我得到的只是undefined。 Stackoverflow 上也存在类似的问题,但不适用于我的情况。知道这会导致什么吗?

我的路由控制器正在 Mongoose 模型中调用 findByCredentials 函数:

控制器

static login(req, res) {
    User.findByCredentials(req.body.email, req.body.password)
      .then(user => {
        return user.generateAuthToken().then(token => {
          res.header("x-auth", token).json(user);
        });
      })
      .catch(error => {
        res.status(400).json({ message: "Invalid credentials." });
      });
  }

型号

userSchema.statics.findByCredentials = function(email, password) {
  return this.findOne({ email }).then(user => {
    if (!user) {
      Promise.reject();
    }
    return new Promise((resolve, reject) => {
      bcrypt.compare(password, user.password, (err, res) => {
        res ? resolve(user) : reject();
      });
    });
  });
};

【问题讨论】:

  • 你能发布你的generateAuthToken()方法吗?
  • Promise.reject(); 你没有遗漏退货声明吗?根据该回调中的逻辑,这似乎是您想要的。

标签: javascript node.js mongoose promise


【解决方案1】:

错误undefined 来自您的Promise.reject(),您没有将任何错误消息传递给它,因此您实际上是在抛出未定义的。

它没有被登录捕获,因为你没有从你的findByCredentials方法返回它。

解决方案:

userSchema.statics.findByCredentials = function(email, password) {
    return this.findOne({ email }).then(user => {
        if (!user) {
            return Promise.reject('User not available');
        }

        return new Promise((resolve, reject) => {
            bcrypt.compare(password, user.password, (err, res) => {
                res ? resolve(user) : reject();
            });
        });
    });
};

【讨论】:

    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多