gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:47:08 26 4
gpt4 key购买 nike

如果过期,这个拦截器应该刷新我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com