Skip to content

Instantly share code, notes, and snippets.

@linux08
Last active October 4, 2019 21:24
Show Gist options
  • Save linux08/cc2b186848d6dd62413564a7ce6f884e to your computer and use it in GitHub Desktop.
Save linux08/cc2b186848d6dd62413564a7ce6f884e to your computer and use it in GitHub Desktop.
import Axios from 'axios';
import JwtDecode from 'jwt-decode';
const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IkFiaW1ib2xhMTMwQGdtYWlsLmNvbSIsImlhdCI6MTU3MDIyMzQyNCwiZXhwIjoxNTcwMjIzNjA0fQ.fIMfLpVZOjt9W1Kk6gSippRCA8XvRsOo94jQkC1lSXE";
const axios = Axios.create({
baseURL: 'https://url.com',
timeout: 80000,
headers: {
'Content-Type': 'application/json',
},
});
axios.interceptors.request.use(
async config => {
config.headers['x-access-token'] = token;
const currentTime = Date.now() / 1000;
const decoded = JwtDecode(token);
if(currentTime > decoded.exp ){
const tokenResponse = await refreshToken();
config.headers['x-access-token'] = tokenResponse.token;
return config;
}
return config;
},
error => {
// Do something with response error
console.log('API ERR:', error.message);
return Promise.reject(error);
},
);
function refreshToken () {
return new Promise((resolve, reject) => {
Axios.get('https://url.com/refresh').then((response) => {
resolve(response.data);
}).catch((error) => {
reject(error);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment