繁体   English   中英

HTTP请求发送时如何在React JS中显示错误消息?

[英]how to show error message in react js when http request send?

你能告诉我HTTP请求发送时如何在react js中显示错误消息吗?

我在nodejs中提供了一项服务,其中正在发送400状态并显示error message 我想在frontend显示此错误消息。

app.get('/a',(req,res)=>{
    res.status(400).send({message:" some reason error message"})
})

现在,我想在前端显示此错误消息。 on catch I will not get this message

try {
            const r = await axios.get('http://localhost:3002/a');
} catch (e) {
            console.log('===============================================')
            console.log(e)
            console.log(e.data)
            hideLoading();
            setErrorMessage(e.message);
            showErrorPopUp();
        }

on catch我不会收到此message.getting stack of error [![enter image description here][1]][1]

在此处输入图片说明

在这种特殊情况下,最好从服务器使用JSON进行响应:

app.get('/a',(req,res) => {
    res.status(400).json({message:"some reason error message"})
})

因此,在客户端中,您可以轻松读取error.response

try {
  const r = await axios.get('http://localhost:3002/a');
} catch (e) {
  if (e.response && e.response.data) {
    console.log(e.response.data.message) // some reason error message
  }
}

此处阅读有关处理axios中捕获的错误的更多信息

这是一个非常主观的问题。 您可能需要使用一些中间件以更好的方式(例如redux-saga或redux-thunk)处理异步操作。

该方法将在您的商店中定义错误状态。 并且,当您收到错误消息时,请更新状态,并调度操作。

并且,在您的组件(容器)中,您需要具有观察者才能获取更新的错误状态。

try {
  const r = await axios.get('http://localhost:3002/a');
} catch (e) {
  if (e.response && e.response.data) {
    // Dispatch an action here
    console.log(e.response.data.message) // some reason error message
  }
}

作为参考,Dan提供了一个非常基础且很好的教程。 https://egghead.io/lessons/javascript-redux-displaying-error-messages

Axios在request-config中具有validateStatus,您可以在其中将状态列入白名单

https://github.com/axios/axios#request-config

// validateStatus定义是为给定的HTTP响应状态代码解析还是拒绝承诺。 如果validateStatus返回true (或设置为null //或undefined ),则将解决诺言; 否则,诺言将被//拒绝。

axios
  .get("<URL>",{validateStatus: function (status) {
    return (status >= 200 && status < 300) || status==400;
  }})
  .then(function(response) {
    // handle success;
  })
  .catch(function(response) {
    // handle error
  })
  .finally(function(error) {
    // always executed
  }); ```

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM