客户端中的错误对象未显示错误消息

时间:2020-06-26 08:20:37

标签: node.js reactjs express redux

我是开发全栈应用程序的初学者。我目前正在构建用户登录的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动作来发出请求 这是我的React代码:

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);
  }
};

当我console.log错误消息时,我得到的是Request failed with status code 404而不是错误消息,例如{ message: "No user with that email" }。但是当我向邮递员发出请求时,却得到了错误消息{ message: "No user with that email" }。是否可以在客户端显示此信息?因为error.message似乎无效

1 个答案:

答案 0 :(得分:0)

我在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 (error) {
    dispatch({ type: LOG_IN_FAILED });
    console.log(error.response.data); //find the error object from the backend incase of an error
  }
};

有关更多信息,请查看https://github.com/axios/axios/issues/960

相关问题