【问题标题】:AXIOS and FETCH not getting custom errors in NODE JSAXIOS 和 FETCH 在 NODE JS 中没有出现自定义错误
【发布时间】:2020-11-29 02:37:46
【问题描述】:

我试图捕捉我在后端创建的自定义错误,但 Axios 和 fetch 没有得到 res.status(401).json({msg:"custom error name"}) 我一直在收到 catch 的响应,但没有错误,没有 msg

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

【问题讨论】:

    标签: javascript node.js reactjs axios fetch


    【解决方案1】:

    试试这个:

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

    【讨论】:

      【解决方案2】:

      对于发送错误或任何响应,您应该这样写。

      res.status(422).send({ success: false, error: "User already exist!" });
      

      【讨论】:

        【解决方案3】:

        axios 中的错误处理与其他的略有不同。在这里,您在catch 块中的错误对象中获得response 对象。我建议您记录响应,然后进行相应处理。

        一个例子是这样的:

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

        【讨论】:

          【解决方案4】:

          我遇到了同样的问题,我想出了解决这个问题的方法。你可以试试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)
          })
          

          【讨论】:

            猜你喜欢
            • 2018-12-24
            • 1970-01-01
            • 2022-01-26
            • 2016-10-11
            • 2021-07-02
            • 2015-07-06
            • 1970-01-01
            • 1970-01-01
            • 2018-06-21
            相关资源
            最近更新 更多