你能告诉我如何在发送http请求时在react js中显示错误消息吗?
我在nodejs中创建了一个服务,我在其中发送400
状态和错误消息
。我想在前端
上显示此错误消息。
app.get('/a',(req,res)=>{
res.status(400).send({message:" some reason error message"})
})
现在我想在前端显示此错误消息。在 catch 时我不会收到此消息
。
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
我不会收到此消息。获取错误堆栈
[![在此处输入图像描述][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 中捕获的错误的更多信息 here
关于javascript - 当http请求发送时,如何在react js中显示错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57583761/