Alright, So I'd like to add a response interceptor to my global axios config, that retries a request once if it gets a 401 error, after refreshing the token.
This is my current global axios config:
import axios from "axios";
export default axios.create({
baseURL: process.env.REACT_APP_API,
headers: {
"content-type": "application/json"
},
responseType: "json"
});
Now I've did research my issue has been addressed here, however, I'm not aware how I can attach or use the interceptor function in the answer there to my axios config file (after I edit it to my needs ofc) the interceptor function looks like this:
createAxiosResponseInterceptor() {
const interceptor = axios.interceptors.response.use(
response => response,
error => {
// Reject promise if usual error
if (errorResponse.status !== 401) {
return Promise.reject(error);
}
/*
* When response code is 401, try to refresh the token.
* Eject the interceptor so it doesn't loop in case
* token refresh causes the 401 response
*/
axios.interceptors.response.eject(interceptor);
return axios.post('/api/refresh_token', {
'refresh_token': this._getToken('refresh_token')
}).then(response => {
saveToken();
error.response.config.headers['Authorization'] = 'Bearer ' + response.data.access_token;
return axios(error.response.config);
}).catch(error => {
destroyToken();
this.router.push('/login');
return Promise.reject(error);
}).finally(createAxiosResponseInterceptor);
}
);
}
Many thanks!