javascript - 即使在成功的 Rest API 调用完成后,Axios 也会发布进入 catch 块
问题描述
我的 axios 发布请求在不成功的 401 场景中没有返回 API 返回的值。当它是一个成功的场景时,它工作得很好。
我的重置密码 API 返回状态代码和每次调用的消息。当我使用 post man 测试其输出以重置密码时,提供不正确的当前密码,我得到
邮递员输出:
statusCode: 401,
headers: {
.......
........
},
body: "{"code":"NotAuthorizedException","name":"NotAuthorizedException","message":"Incorrect username or password."}" <--- This is the body output
但在我的 axios 帖子中,它进入了 catch 块:
await Axios.post(resetAPIUrl, resetParams, config).then(value=> {
console.log(`Returned data ----> ${JSON.stringify(value)}`);
resolve(value);
}).catch(error=>{
console.log(`Failing--->${error}`)
reject(error)
});
这是我在 Axios 帖子的 catch 块中遇到的错误:
Error: Request failed with status code 401
错误原因是正确的。但为什么它会进入 catch 块?它成功地完成了这个过程。直接从 post man 调用 API 给了我正确的输出结构。
解决方案
拦截器就是答案。由于 Axios 不会将 200 以外的任何响应视为成功场景,因此可以使用拦截器来捕获其他响应:
{
Axios.interceptors.request.use(req=>{
console.log(`This is the request ---> ${req.method} ${req.url}`)
return req;
})
Axios.interceptors.response.use(res => {
console.log(`res status ---> ${res.status}`)
resolve(res)
return res;
}, (error)=>{
console.log(`This is the error status ---> ${error.response.status}`)
if(error.response.status === 401){
resolve(error.response);
}
})
await Axios.post(resetAPIUrl, resetParams, config);
推荐阅读
- excel-2016 - 如何在 Excel 365 中修改连接字符串
- ios - 定义包含行、类和一般格式的自定义 NSAssert
- azure - 多租户 SaaS 应用程序的身份验证
- javascript - Twitter API Javascript 扩展模式
- php - 每隔几秒刷新一次从 MYSQL 填充的 textarea
- spring-boot - 如果给定的参数集合为空,则弹簧数据 jpa 查询选择所有行
- node.js - 为 npm 注册表 URL 设置用户名和密码
- c# - C#:在表单之外获取鼠标点击位置 - 失去焦点,在外面点击后 form1 不在前面
- python - CLI 路由不适用于 @hug.extend_api()
- android - 如何在 SQLite Android Studio 中加入表