Skip to content

Instantly share code, notes, and snippets.

@tesarwijaya
Created July 17, 2017 04:32
Show Gist options
  • Save tesarwijaya/bf05f4b8c8a3136e72f46253b56285fc to your computer and use it in GitHub Desktop.
Save tesarwijaya/bf05f4b8c8a3136e72f46253b56285fc to your computer and use it in GitHub Desktop.
How to get a new token after token expired in axios
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