首页 > 解决方案 > 即使在成功的 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 给了我正确的输出结构。

标签: javascriptreactjstypescriptaxios

解决方案


拦截器就是答案。由于 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);


推荐阅读