Answer the question
In order to leave comments, you need to log in
How to implement axios.interseptors to save and update token?
Hello. Please tell me how to implement interseptor in axios to save the default token and update?
Below is the code I currently have and it doesn't work. I still end up with a 401 error in the console.
var APIKit = axios.create({ baseURL: url });
;
export const setClientRefreshToken = async () => {
let refTokenStorage = await AsyncStorage.getItem("refToken");
let payload = {
refreshToken: refTokenStorage,
};
APIKit.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const originalRequest = error.config;
if (error.response.status === 401 && originalRequest.url) {
//переход на логин скрин
return Promise.reject(error);
}
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
return APIKit.post("/authentication/refresh", payload).then((res) => {
if (res.status === 201) {
APIKit.defaults.headers.common["Authorization"] =
"Bearer " + localStorageService.getAccessToken();
//переход на скрин где был баг
return APIKit(originalRequest);
}
});
}
}
);
};
export const setClientToken = async () => {
let token = await AsyncStorage.getItem("token");
APIKit.interceptors.request.use(
(config) => {
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
}
return config;
},
(error) => {
Promise.reject(error);
}
);
};
export default APIKit;
var APIKit = axios.create({ baseURL: url });
const refreshAuthLogic = async (failedRequest) => {
let refTokenStorage = await AsyncStorage.getItem("refToken");
let payload = {
refreshToken: refTokenStorage,
};
APIKit.post("/authentication/refresh", payload).then((rt) => {
setClientToken(rt.data.token);
return Promise.resolve();
});
};
createAuthRefreshInterceptor(APIKit, refreshAuthLogic)
export const setClientToken = async (token) => {
// let token = await AsyncStorage.getItem("token");
APIKit.interceptors.request.use(
(config) => {
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
}
return config;
},
(error) => {
Promise.reject(error);
}
);
};
export default APIKit;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question