Skip to content

Instantly share code, notes, and snippets.

@sidigi
Created July 10, 2019 14:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sidigi/af90ce5a7f0d2412636d898b5871dfa6 to your computer and use it in GitHub Desktop.
Save sidigi/af90ce5a7f0d2412636d898b5871dfa6 to your computer and use it in GitHub Desktop.
Nuxt Refresh token request
export default function ({$axios, app}) {
$axios.onResponseError(error => {
const code = parseInt(error.response && error.response.status);
let originalRequest = error.config;
if ([401, 403].includes(code)) {
originalRequest.__isRetryRequest = true;
let refresh_token = app.$auth.getRefreshToken(app.$auth.$storage.state.strategy).replace('Bearer ', '');
return new Promise((resolve, reject) => {
$axios
.post(`http://bgs-auth.local/api/refresh-token`, {refresh_token})
.then(response => {
if (response.status == 200) {
app.$auth.setToken(app.$auth.$storage.state.strategy,'Bearer ' + response.data.access_token);
app.$auth.ctx.app.$axios.setHeader('Authorization', 'Bearer ' + response.data.access_token);
app.$auth.setRefreshToken(app.$auth.$storage.state.strategy, 'Bearer ' + response.data.refresh_token);
originalRequest.headers['Authorization'] = `Bearer ${response.data.access_token}`;
}
resolve(response);
})
})
.then(res => {
return $axios(originalRequest);
}).catch(e => {
app.$auth.logout();
setTimeout(() => {
app.router.push('/login');
})
});
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment