javascript - 使用 axios 时从服务器获取 json 错误响应
问题描述
Axios.post('http://localhost:3001/signup',
{
name:name,
email:email,
password:password
})
.then((res)=>{
if(res.data){
M.toast({html: 'Response successfully recorded!'}) //giving the message
}
console.log(res);
})
我正在使用这段代码在我的反应应用程序中将 POST 请求发送到后端服务器,但无法获得服务器给出的 json 错误,我得到了这个:-
xhr.js:177 POST http://localhost:3001/signup 422 (Unprocessable Entity)
Uncaught (in promise) Error: Request failed with status code 422
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
如何获取服务器给出的用于处理前端错误的json错误?
解决方案
您需要使用.catch
:
Axios.post('http://localhost:3001/signup',
{
name:name,
email:email,
password:password
})
.then((res)=>{
if(res.data){
M.toast({html: 'Response successfully recorded!'}) //giving the message
}
console.log(res);
}).catch((err) => console.log(err));
.then
表示请求成功。
.catch
表示请求失败。
推荐阅读
- c - 为什么在 C 中不允许定义括号括起来的指针类型的宏?
- unity3d - Unity 的 Pyshics.RaycastAll 层参数有问题
- wordpress - Wordpress if/while 或 while 循环
- c++ - CAboutDlg aboutDlg 和局部变量
- json - 逻辑应用程序 - 努力编写 JSON 并追加到数组
- java - Java:从自己的源代码和标准库中导入类
- python - 为什么 python 的内置数学运算符在处理大数时很慢?
- python - 如何在 Python 字典中找到值最多(不是最高)的键?
- sql - SQL:SELECT date BETWEEN 错误(postgres)
- autodesk-forge - 需要 Forge Viewer 和 Gyroscope 的帮助。需要将初始相机位置固定到 Bim 模型中的当前视图