Answer the question
In order to leave comments, you need to log in
How to properly handle getting an access token in interceptors on axios?
There is the following situation, to which I can not find an approach:
1. We call some method (GET, POST ...)
2. In interceptors, we check the token for an expired period
3. If the token is expired, we suspend the execution of the current request
4. We receive a token
5 We continue the execution of the query that we remembered before
Perhaps there are ready-made templates for solving such problems?
Or any suggestion? Tip?
I will be grateful for any information.
export const http = axios.create();
const currentExecutingRequests = {};
http.interceptors.request.use(
(req) => {
let originalRequest = req;
if (currentExecutingRequests[req.url]) {
const source = currentExecutingRequests[req.url];
delete currentExecutingRequests[req.url];
source.cancel('Отмена запроса');
}
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
originalRequest.cancelToken = source.token;
currentExecutingRequests[req.url] = source;
return originalRequest;
},
(err) => {
return Promise.reject(err);
}
);
Answer the question
In order to leave comments, you need to log in
My solution, which I use when authorizing to QC
import _ from 'lodash';
const mainFetch = axios.create();
export const issueToken = () => {
return new Promise((resolve, reject) => {
return keycloak.updateToken(30000).success((refreshed) => {
if (refreshed) {
resolve(keycloak.token);
sessionStorage.setItem("kctoken", `${keycloak.token}`);
} else {
console.log('not refreshed ' + new Date());
}
}).error(() => {
reject();
keycloakLogout();
});
});
}
mainFetch.interceptors.request.use((config) => {
let originalRequest = config;
if (keycloak.isTokenExpired(30000)) {
return issueToken().then((token) => {
_.set(originalRequest, 'headers.Authorization', `Bearer ${token}`);
return Promise.resolve(originalRequest);
});
} else {
_.set(config, 'headers.Authorization', `Bearer ${sessionStorage.getItem("kctoken")}`);
}
return config;
}, (err) => {
return Promise.reject(err);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question