【问题标题】:Error object in the client side not showing the error message客户端中的错误对象未显示错误消息
【发布时间】:2020-06-26 08:20:37
【问题描述】:

我是开发全栈应用程序的初学者。我目前正在构建用户登录的 React、Node 和 Express.js 应用程序。我在后端有错误检查,我想在客户端显示它。

这是我的节点代码:


app.post("/api/login",async(req,res)=>{
  try {
    const { email, password } = req.body;
      const user = await User.findOne({ email });
      if (!user) {
        return res.status(404).send({ message: "No user with that email" });
      }
      const isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch) {
        return res.status(401).send({ message: "Passwords do not match" });
      }
      res.send(user);
  } catch (error) {
    res.status(500).send(error);
    
  }
})

我正在使用 redux 操作来发出请求 这是我的反应代码:

export const logIn = credentials => async dispatch => {
  try {
    const res = await axios.post("/api/login", credentials);
    console.log(res.data);
    dispatch({
      type: LOG_IN,
      payload: res.data
    });
  } catch (error) {
    dispatch({ type: LOG_IN_FAILED });
    console.log(error);
  }
};

当我控制台记录 error.message 时,我收到的是 Request failed with status code 404 而不是错误消息,例如 { message: "No user with that email" }。但是当我向邮递员发出请求时,我收到的是错误消息 { message: "No user with that email" }。有没有办法可以在我的客户端显示?因为error.message 似乎不起作用

【问题讨论】:

  • 该消息仍存在于error 对象中。试试console.log(error.message)
  • @SagarChilukuri 当我console.log(error) 我得到Error: Request failed with status code 404 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61) 而当我console.log(error.message) 我得到Request failed with status code 404
  • console.log(error) 更改为console.log(error.message)
  • 当我console.log(error.message) 我得到Request failed with status code 404
  • 如果您点击了正确的地址,您是否在浏览器开发工具中检查了“网络选项卡”?

标签: node.js reactjs express redux


【解决方案1】:

我在error.response.data 上找到了错误对象,其中包含来自我的后端的实际错误{ message: "No user with that email" },因此代码如下所示:

export const logIn = credentials => async dispatch => {
  try {
//make request to backend (with axios in my case)
 } catch ({reponse}) {
    dispatch({ type: LOG_IN_FAILED });
    console.log(response.data); //find the error object from the backend incase of an error
  }
};

欲了解更多信息,请查看https://github.com/axios/axios/issues/960

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2023-04-09
    • 2020-07-02
    • 2016-09-25
    • 1970-01-01
    相关资源
    最近更新 更多