【问题标题】:How to get a response from express server about an error using axios in react app如何在反应应用程序中使用 axios 从快速服务器获取有关错误的响应
【发布时间】:2019-10-24 03:58:10
【问题描述】:

我正在使用 react 和 express。在反应应用程序中,我想使用 axios.post 将用户的凭据发送到快递服务器,并希望收到它的响应。从响应中我想提取消息和状态。它看起来像这样:

handleSubmit = e => {
    e.preventDefault();
    const { email, password } = this.state;
    axios
      .post("/api/users/login", {
        email,
        password
      })
      .then(res => console.log(res.data.msg, res.status))
      .catch(err => console.log(err));
  };

在后端,我使用猫鼬模型来确定用户是否已存在于数据库中。

router.post("/login", (req, res) => {
  const { email, password } = req.body;

  User.findOne({ email })
    .then(user => {
      if (!user) return res.status(400).json({ msg: "No such user in the DB" });

      bcrypt.compare(password, user.password).then(isMatch => {
        if (!isMatch) {
          return res.status(400).json({ msg: "Wrong password" });
        }

        req.session.userId = user.id;
        res.status(200).json({ msg: "You have logged in" });
      });
    })
    .catch(err => console.log("Error in catch in findOne"));
});

如果一切顺利,并且数据库中存在具有这些凭据的用户,我会按预期在控制台中收到消息“您已登录”和状态 200 但 如果发生错误,我不会收到 axios 响应自定义错误消息,例如“数据库中没有此类用户”或“密码错误”,而是收到默认错误,我猜,它看起来像这样:

xhr.js:166 POST http://localhost:3000/api/users/login 400 (Bad Request)
Login.js:21 Error: Request failed with status code 400
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)

我的问题是:如果出现任何问题,我如何才能获得自己的错误消息而不是默认消息。例如:如果密码不正确,我希望在 axios 响应“数据库中没有此类用户”中收到此消息。

【问题讨论】:

  • 你发回的msg字段不还是自定义的吗?
  • 是自定义的,但是如果密码错误或用户不在数据库中,我在axios响应中没有收到。我刚刚在控制台中收到这条消息:xhr.js:166 POST localhost:3000/api/users/login 400 (Bad Request)

标签: reactjs express axios


【解决方案1】:

让 axios 捕获服务器响应:

在 axios 的 catch 中从 console.log(error) 修改为 console.log(error.response)

参考:https://github.com/axios/axios/issues/960#issuecomment-309287911


对于 react 中的自定义错误处理:

向您的状态添加一个新变量error: null
在 axios 中,在其块内的 .then(res=> {}) 中,您有条件地抛出错误。
例如:

.then( res => {
 if(res.status === 400) {throw new Error("your custom message")}
   ...your code...
 })

The syntax of Error

新错误([消息[,文件名[,行号]]])

接下来会在catchblock 中捕获抛出的错误,即:

.catch(err => this.setState({error:err}))

现在错误的内容在状态中的error 对象内。
要访问和显示您的自定义消息,具体取决于您想要的位置:

this.state.error.message(this.)props.error.message

【讨论】:

  • 谢谢,它成功了,但你能解释一件事吗?我在想,如果我使用这样的验证:if (!user) return res.status(400).json({ msg: "No such user in the DB" }) 我可以在axios.then(res => res.data.msg) 部分中获得我的自定义错误消息。我以为当我使用return res.status... 时,我会结束请求并将响应发送到前端。我的自定义错误怎么会出现在 .catch 部分。我想我错过了一些关于快递的东西?
  • @madjack99 我很高兴它对你有用,我也学到了一些东西。我不想假装我是专家,但据我所知(我简要地使用 react+express+mongoose 堆栈),你必须在你的状态中添加一个变量 error: null,并在 then(res=> {...}) 块中,你有条件地抛出一个错误,如:if(res.status === 400) {throw new Error "your message")。它将在下一个捕获块中捕获,即catch(err => this.setState({error:err}),现在取决于您要在哪里显示它是this.state.error.message(this.)props.error.message
  • @madjack99 有用吗?如果是这样,我会将其添加到答案中。
  • @madjack99 感谢您的反馈,我真的很关心我想解决的问题。顺便说一句,我没有对你投反对票,而是会投你一票,因为我发现你的问题不仅有效,而且非常有趣。
猜你喜欢
  • 1970-01-01
  • 2021-02-07
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多