我使用令牌作为授权,当令牌过期时,我想使用刷新令牌创建一个新令牌。我可以用 axios 库做到这一点,但我找不到如何用 umi 请求做到这一点。有人将下面给出的代码示例翻译成 umi 请求拦截器示例吗?
这个 axios 拦截器响应我的刷新令牌操作。
let isRefreshing: boolean = false;
let failedQueue: any = [];
const processQueue = (error: any, token: any = null) => {
failedQueue.forEach((prom: any) => {
if (error) {
prom.reject(error);
} else {
prom.resolve(token);
}
});
failedQueue = [];
};
axios.interceptors.response.use(
async response => {
return response;
},
async error => {
debugger;
const originalRequest = error.config;
if (error.response) {
const status = error.response.status;
const refreshToken = getStoredUserAuth().refreshToken;
if (status === 401 && !originalRequest._retry) {
if (isRefreshing) {
return new Promise(function(resolve, reject) {
failedQueue.push({ resolve, reject });
})
.then(token => {
originalRequest.headers["Authorization"] = "Bearer " + token;
return axios(originalRequest);
})
.catch(err => {
return Promise.reject(err);
});
}
originalRequest._retry = true;
isRefreshing = true;
return new Promise(function(resolve, reject) {
refreshAccessToken(refreshToken)
.then(response => {
if (response.status === 200) {
if (response.data.token) {
setAuthStatus(response.data);
axios.defaults.headers.common["Authorization"] =
"Bearer " + response.data.token;
originalRequest.headers["Authorization"] =
"Bearer " + response.data.token;
}
processQueue(null, response.data.token);
resolve(axios(originalRequest));
} else {
throw new Error();
}
})
.catch(err => {
//console.log(err);
failedQueue = [];
setUnauthStatus();
source.cancel("Session time out");
processQueue(err, null);
reject(err);
})
.then(() => {
isRefreshing = false;
});
});
}
} else {
debugger;
errorHandler(error);
}
return Promise.reject(error);
}
);
我用的是ant design pro V5版本,所以我尝试用umi request刷新token,但是我做不到,因为在axios库中,我不能写umi request,我无法建立它的逻辑。那么任何人都可以为 umi 请求编写上面相同的示例(axios.interceptors.response)吗?
const requestInterceptors = (url: string, options: RequestOptionsInit) => {
if (tokenService.check()) {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${tokenService.parse()?.token}`,
};
return {
url,
options: { ...options, headers },
};
}
return {
url,
options: { ...options },
};
};
const responseInterceptors = (response: Response, options: RequestOptionsInit) => {
// I could'nt this part for refresh token like axios interceptors. I need help for that
return response;
}
export const request: RequestConfig = {
errorHandler,
requestInterceptors: [requestInterceptors],
responseInterceptors: [responseInterceptors]
};