目前,我在“ Javascript”代码中无法兑现承诺。它不断抛出“ TypeError:res.status(...)。json(...)。catch不是函数”,我猜我的诺言在代码行的某个地方是错误的。

这是我到目前为止的内容:

route.js

route.post('/login', function(req, res) {
    log.login(req,res).then((post)=>{
      res.status(200).json({message: post})
      .catch((error)=>{
        res.status(400).json({message: error})
      })
    })
  });


和login.js

function login(req,res){
    console.log('here', req.body.email, req.body.password)
      if (!req.body.email || !req.body.password) {
         return Promise.resolve({success: false, msg: 'Please pass email and password.'});
      } else {
          return Promise.resolve(User.findOne({
              'local.email': req.body.email
        })).exec().then((user)=> {
          if (!user) {
            return Promise.reject({success:false, msg: 'Authentication failed. User not found'}); //res.send({success: false, msg: 'Authentication failed. User not found.'});
          } else {
            // check if password matches
              if(user.validPassword(req.body.password)) {
              // if user is found and password is right create a token
                var token = jwt.sign(user.id, config.secret);
              // return the information including token as JSON
                return Promise.resolve({success: true, token: 'JWT ' + token});
            } else {
                return Promise.reject({success: false, msg: 'Authentication failed. Wrong password.'});
            }
          }
        }).catch((errors)=>{
            return ({message: "Could not propose login"});
        })
      }
  }


module.exports = {
  login
}

最佳答案

我相信您刚刚错过了})固定代码:

route.post('/login', function(req, res) {
    log.login(req,res).then((post) => {
        res.status(200).json({message: post})
      })
      .catch((error) => {
        res.status(400).json({message: error})
      })
    })
  });

10-02 15:54