AXIOS 和 FETCH 在 NODE JS 中没有出现自定义错误

我正在尝试捕获我在后端创建的自定义错误,但是 Axios 和 fetch 没有得到res.status(401).json({msg:"custom error name"}) 我已经从 catch 得到响应但是没有错误没有消息


try {

  const loginUser = { email: user.email, password: user.password };

  const loginRes = await Axios.post(

    "http://localhost:4000/snackhub/login",

    loginUser

  );

  localStorage.setItem("auth-token", loginRes.data.token);

  dispatch(fetchUsers());

  history.push("/");

} catch (err) {

  console.log(err.response);

  err.response.data.msg && console.log(err.response.data.msg); //hopefully i can display this thhe custom error from the backend

}

以下是后端错误的示例:


 const { error } = await logInValidation(req.body);

if (error) return res.status(400).json({ msg: error.message[0].details }); //is there something wrong in my syntax here?


const userExists = await Customer.findOne({ email: email });

if (!userExists)

  return res.status(400).json({ msg: "email is not registered" });


狐的传说
浏览 232回答 4
4回答

素胚勾勒不出你

试试这个:axios.post("http://localhost:4000/snackhub/login",    loginUser).then(res => {                        },error => {});

弑天下

对于发送错误或您应该这样写的任何响应。res.status(422).send({ success: false, error: "User already exist!" });

守着星空守着你

中的错误处理axios与其他的略有不同。在这里,您在块中获取response错误对象中的对象。catch我建议您记录响应,然后相应地进行处理。一个例子是这样的:axios.post(url, data).then(res => {        // do good things}).catch(err => {    if (err.response) {      // client received an error response (5xx, 4xx)    } else if (err.request) {      // client never received a response, or request never left    } else {      // anything else    }})

梵蒂冈之花

我遇到了同样的问题,我想出了解决这个问题的方法。你可以试试console.log(error.response.data)。这将打印从您的服务器发送的 JSON 响应...即:res.status({message: "Custom error message"}) 可以在客户端使用 axios 访问:axios.get(url).then(response => {    // your logic }).catch(err => {    console.log(err.response.data.message)})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript