typescript - 如何将自定义属性添加到 axios 配置?

标签 typescript axios

如果过期,这个拦截器应该刷新我的 token 。

declare module "axios" {
  export interface AxiosRequestConfig {
    _retry?: boolean;
  }
}
axios.interceptors.response.use(
  (res) => res,
  (error: AxiosError) => {
    const originalRequest = error.config;
    console.log(originalRequest._retry); // always undefined
    if (error?.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      return axios
        .post("/auth/refresh-token", {}, { withCredentials: true })
        .then((res) => {
          if (res.status === 201) {
            return axios(originalRequest);
          }
        })
    }
    return Promise.reject(error);
  }
);

关键点是我添加到请求配置中的 _retry 属性,因此它应该可以防止无限循环。但恰恰相反!它创建了一个无限循环,因为 _retry 总是 undefined

我在他们的 Github 页面上发现了一些问题,但没有找到解决方案。

编辑: Su Yu 用最新版本的 axios 尝试了这段代码,它成功了。所以也许这是一个错误。我在 axios repo 中创建了一个问题: https://github.com/axios/axios/issues/3920

我有一个问题:如果刷新 token 请求也返回 401 错误怎么办?

最终编辑: 最后,我解决了它。我存入无限循环,因为如果刷新 token 过期,刷新 token 请求会返回 401 错误。所以我将其更改为 400,一切都按预期进行。我现在要打自己耳光!

最佳答案

您使用哪个版本的 axios?看来 axios 在 0.19.2 上解决了这个问题。您可以查看拉取请求 Fixing custom config options .

我已经尝试了最新版本(0.21.1)的 axios,自定义配置工作正常。

关于typescript - 如何将自定义属性添加到 axios 配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68572355/

相关文章:

angular - 如何使用 Typescript 在 Angular 2 中使用 Google 登录

css - 基于多个按钮选择的过滤器

javascript - Puppeteer 等待页面和 setTimeout 在 Firebase 云功能中不起作用

angular - 在非 Angular 类中获取注入(inject)的依赖项

javascript - request post 与 axios post 解析不同的结果

safari - Axios GET 在 Safari 浏览器中不起作用

reactjs - 我不断收到“'Object is of type ' 未知”错误

TypeScript:获取属性的类型

javascript - 带有 node.js 的 Axios - ReferenceError : XMLHttpRequest is not defined

javascript - 在 react 中使用 Axios 在一个 componentDidMount 中调用多个 API