为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

狐的传说 2022-12-29 09:48:45
我正在尝试捕获我在后端创建的自定义错误,但是 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" });
查看完整描述

4 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

试试这个:


axios.post("http://localhost:4000/snackhub/login",

    loginUser)

.then(res => {

                        

},

error => {


}

);


查看完整回答
反对 回复 2022-12-29
?
弑天下

TA贡献1818条经验 获得超8个赞

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

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


查看完整回答
反对 回复 2022-12-29
?
守着星空守着你

TA贡献1799条经验 获得超8个赞

中的错误处理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

    }

})


查看完整回答
反对 回复 2022-12-29
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

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

})


查看完整回答
反对 回复 2022-12-29
  • 4 回答
  • 0 关注
  • 231 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号