Created
July 17, 2017 04:32
-
-
Save tesarwijaya/bf05f4b8c8a3136e72f46253b56285fc to your computer and use it in GitHub Desktop.
How to get a new token after token expired in axios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios' | |
import store from '../store' | |
import qs from 'qs' | |
export const http = axios.create({ | |
baseURL: 'http://localhost:8000/api/', | |
header: { | |
'Content-Type': 'application/x-www-form-urlencoded' | |
} | |
}) | |
http.interceptors.response.use(function (response) { | |
return response | |
}, function (error) { | |
const originalRequest = error.config | |
console.log(originalRequest) | |
if (error.response.status === 401 && !originalRequest._retry) { | |
originalRequest._retry = true | |
//get refresh token | |
const refreshToken = store.getters['userInfo/getOauth2'].refresh_token | |
//make refresh token request | |
return http.post( | |
http.defaults.baseURL + 'refreshtoken', | |
qs.stringify({username: store.getters['userInfo/getUser'].username, grant_type: 'refresh_token', refresh_token: refreshToken}), | |
{ | |
auth: { | |
username: 'web-application-manager', | |
password: '6cd316c28d8456b9fd7577cc03acfd5f029b9068' | |
} | |
}) | |
.then((responseData) => { | |
// set new oauth2 info | |
store.dispatch('userInfo/set', responseData.data) | |
http.defaults.headers.common['Authorization'] = 'Bearer ' + store.getters['userInfo/getOauth2'].access_token | |
originalRequest.headers['Authorization'] = 'Bearer ' + store.getters['userInfo/getOauth2'].access_token | |
//retry failed request | |
return http(originalRequest) | |
}).catch(function (error) { | |
console.log(error) | |
}) | |
} | |
return Promise.reject(error) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment