你能告诉我当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
我不会收到此消息。继续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
easily
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 中捕获的错误的更多信息here https://github.com/axios/axios#handling-errors
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)