如何显示后端错误信息而不是状态码

How to display the back-end error message instead of status code

我创建了一个后端服务器并将其 post 编辑到 Heroku,现在我正在使用服务器 URL 到 post 并从中获取数据。但是,当我显示一条错误消息时,它给我的是状态代码而不是实际错误。

我的后端登录代码。

 export const loginUser = asyncHandler(async(req, res) => {
  const { email, password } = req.body;

  const user = await userModel.findOne({ email });

  const token = generateToken(user._id)

  if(user && (await user.matchPassword(password))){
    res.json({
      _id:user._id,
      username: user.username,
      email: user.email,
      profilePic:user.profilePic,
      admin:user.admin,
      token:token,

    });

  } else {
    res.status(400)
    throw new Error("invalid email or password please check and try again!");
  }

});

我起诉 redux 后的用户操作代码

    export const login = (email, password) => async (dispatch) => {
    try {
    dispatch({
      type: USER_LOGIN_REQUEST,
    });

    const url = `${process.env.REACT_APP_SERVER_URL}api/loginuser`;
    const config = {
      headers: {
        "Content-type": "application/json",
      },
    };
    const { data } = await axios.post(
      url,
      {
        email,
        password,
      },
      config
    );

    dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    });
    localStorage.setItem("userInfo", JSON.stringify(data));
   } catch (error) {
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

前端显示错误

您需要 return 响应而不是抛出错误:

res.status(400)
res.json({
 message: "invalid email or password please check and try again!"
});

首先,您需要像这样从后端发送一条错误消息:

 export const loginUser = asyncHandler(async(req, res) => {
  const { email, password } = req.body;

  const user = await userModel.findOne({ email });

  const token = generateToken(user._id)

  if(user && (await user.matchPassword(password))){
    res.json({
      _id:user._id,
      username: user.username,
      email: user.email,
      profilePic:user.profilePic,
      admin:user.admin,
      token:token,

    });

  } else {
    res.status(400).json({errorMessage :"invalid email or password please check and try again!" })

  }

});

然后在 React 部分获取它(一定要阅读我在那之后添加的评论console.log):

 export const login = (email, password) => async (dispatch) => {
    try {
    dispatch({
      type: USER_LOGIN_REQUEST,
    });

    const url = `${process.env.REACT_APP_SERVER_URL}api/loginuser`;
    const config = {
      headers: {
        "Content-type": "application/json",
      },
    };
    const { data } = await axios.post(
      url,
      {
        email,
        password,
      },
      config
    );

    dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    });
    localStorage.setItem("userInfo", JSON.stringify(data));
   } catch (error) {
    console.log(error); // look at the console, as I may miss the correct retuned error object
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response.data.errorMessage
    });
  }
};