【问题标题】:Handling express error in Next.js with axios使用 axios 处理 Next.js 中的快速错误
【发布时间】:2021-11-25 09:36:50
【问题描述】:

我正在通过对我的 API 的异步调用为我的应用程序构建登录功能。我的问题是,即使 express 抛出错误, .then() 仍然在运行时出现错误,而不是实际的用户和令牌响应。我不确定为什么登录功能没有“捕捉”错误,而是在 .then() 中运行代码。

我的快递功能:

// express funciton to login a user
app.post('/api/users/login', (req, res) => {
  const { email, password } = req.body
  database.getUser(email, password, (error, user) => {
    console.log(error)
    if (error) {
      res.send({ error })

//errors are being handled here and are returned in the result of my 
frontend API call

      return
    }
    const token = jwt.generateToken({ userId: user.id, name: user.name, email: user.email })
    res.send({ token: token, user:user })
  })
})

//getUser function with mySQL query
function getUser(email, password, callback) {
  const query = `
      SELECT id, name, email, password
      FROM users
      WHERE email = ?
  `
  const params = [email]

  connection.query(query, params, (error, results, fields) => {
    if (!results || results.length === 0) {
      callback(Error("Email is incorrect"))
      return
    }

    const user = results[0]

    bcrypt.compare(password, user.password, (error, same) => {
      console.log(error)
      if (error) {
        callback(error)
        return
      }

      if (!same) {
        callback(Error("Password is incorrect"))
        return
      }

      callback(null, user)
    })
  })
}
exports.getUser = getUser

我在 Next.js 中的登录功能:

    const login = async ({ email, password }) => {
        return await axios.post('http://localhost:4200/api/users/login', {
            email: email,
            password: password
        })
            .then((result) => {

//when backend throws error, they are contained here as "result.error" still running these lines of code

                sessionStorage.setItem('token', result.data.token);
                axios.defaults.headers.common['Authorization'] = "Bearer " + result.data.token;
                console.log('user signed in');
            })
            .catch((err) => {

//want errors to be directed here instead so I can properly handle them within the UI

                console.error("Username or password is incorrect!!")
            })
    };

【问题讨论】:

  • 尝试设置错误状态码。 res.status(401).json({ error })
  • 如果有帮助请告诉我

标签: javascript node.js reactjs express next.js


【解决方案1】:

.catch(error) 只有在 axios 承诺本身无法完成时才会出错。

在这种情况下,axios 承诺正确完成,但是,您将返回一个有效的错误代码,说明登录无法完成的原因。

因此,一种方法是在您的 .then(result) 函数中查找该类型的结果并执行某些操作。

类似

.then((result) => {
 if (result.error) { ... return an error message to user ... } 
 else {
  sessionStorage.setItem('token', result.data.token);
  axios.defaults.headers.common['Authorization'] = "Bearer " + 
  result.data.token;
  console.log('user signed in');}
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-24
    • 2021-08-29
    • 2018-01-07
    • 1970-01-01
    • 2018-10-02
    • 2018-12-25
    相关资源
    最近更新 更多