【问题标题】:How can I properly handle request errors with React front end?如何使用 React 前端正确处理请求错误?
【发布时间】:2020-12-13 23:41:48
【问题描述】:

目前我在“/register”路由上设置了我的后端:

registerRouter.post('/', async (req, res) => {
  // Validate submitted registration form
  const { error } = registerValidation(req.body)
  if(error) {
    return res.status(400).send(error.details[0].message)
  }
  try {
    // Check if email exists already
    const user = await User.findOne({ email: req.body.email })
    if(user) {
      return res.status(400).send('Email already exists')
    }
    // If not, begin registering user by hashing the password
    const hashedPassword = await bcrypt.hash(req.body.password, 10)
    const newUser = new User({
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      email: req.body.email,
      password: hashedPassword
    })
    const savedUser = await newUser.save()
    res.send(savedUser)

  } catch(error) {
    res.sendStatus(500)
  }
})

使用 Postman,当我提出正确/不正确的请求时,我会得到正确的响应。但是当我在我的前端发出请求时,如果它是一个不正确的请求,例如密码不够长,缺少必填字段,然后我只收到 400 响应。例如,如何使用错误响应在屏幕上显示错误以供用户查看? 这是我当前用于表单的 onSubmit 函数:

  const register = async event => {
    event.preventDefault()
    axios
      .post('/register', newUser)
      .then(res => console.log(res))
      .catch(err => console.log(err))
  }

【问题讨论】:

标签: reactjs


【解决方案1】:

尝试使用:

 axios
  .post('/register', newUser)
    .catch(function (error) {
       console.log(error.toJSON()); // or maybe exist .toText()
  });

(https://github.com/axios/axios#handling-errors)

也在服务器端进行转换:

return res.status(400).send('Email already exists')

return res.status(400).send({ error: 'Email already exists' });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2022-01-23
    • 1970-01-01
    • 2021-12-29
    • 2019-03-05
    相关资源
    最近更新 更多