【问题标题】:UnhandledPromiseRejectionWarning: TypeError: res.status(...).json(...).catch is not a functionUnhandledPromiseRejectionWarning: TypeError: res.status(...).json(...).catch 不是函数
【发布时间】:2020-08-01 23:01:22
【问题描述】:

当我尝试使用邮递员发布请求时收到错误Type Error: res.status(...).json(...).catch is not a function,不知道我做错了什么。

signin.js

exports.signin = (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    res.status(422).json({
      error: "please enter email and password"
    })
  }
  User.findOne({ email: email })
    .then(SavedUser => {
      if (!SavedUser) {
        return res.status(400).json({
          error: "invalid email or password"
        })
      }
      bcrypt.compare(password, SavedUser.password)
        .then(doMatch => {
          if (doMatch) {
            res.json({
              message: "Successfully Signed in"
            })
          }
          else {
            return res.status(422).json({
              error: "Invalid email or password"
            })
              .catch(err => {
                console.log(err);
              })
          }
        })
    })

}

【问题讨论】:

  • catch 块放在then 块的末尾

标签: node.js mongodb express postman


【解决方案1】:

你放错了.catch(...),应该在.then(...)之后,而不是res.json()


  exports.signin = (req, res) => {
    const { email, password } = req.body
    if (!email || !password) {
      res.status(422).json({
        error: 'please enter email and password'
      })
    }
    User.findOne({ email: email })
      .then(SavedUser => {
        if (!SavedUser) {
          return res.status(400).json({
            error: 'invalid email or password'
          })
        }
        bcrypt.compare(password, SavedUser.password)
          .then(doMatch => {
            if (doMatch) {
              res.json({
                message: 'Successfully Signed in'
              })
            } else {
              return res.status(422).json({
                error: 'Invalid email or password'
              })
            }
          })
          .catch(err => { // .catch goes here
            console.log(err)
          })
      })
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 2021-10-27
    • 2021-09-26
    • 2020-06-26
    • 1970-01-01
    • 2023-03-05
    • 2021-07-13
    • 1970-01-01
    相关资源
    最近更新 更多