Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Kishimotovn/0f95eb7abf7e5b389d6bdc28257b14a4 to your computer and use it in GitHub Desktop.
Save Kishimotovn/0f95eb7abf7e5b389d6bdc28257b14a4 to your computer and use it in GitHub Desktop.
vue-axios
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import { getTokenFromCookie, getTokenFromLocalStorage } from '~/utils/auth'
axios.defaults.baseURL = 'http://0.0.0.0:8181/api/v1'
// Intercept the request to make sure the token is injected into the header.
axios.interceptors.request.use(config => {
if (context) {
const token = context.isServer ? getTokenFromCookie(context.req) : getTokenFromLocalStorage()
config.headers.Authorization = 'Bearer ' + token
console.log('send token', token)
}
return config
})
// Intercept the response and…
axios.interceptors.response.use(response => {
NProgress.done()
if (context) {
// …get the token from the header or response data if exists, and save it.
const token = response.headers['Authorization'] || response.data['token']
if (token) {
console.log('set token', token)
context.store.commit('setToken', token)
}
}
return response
}, error => {
NProgress.done()
// Also, if we receive a Bad Request / Unauthorized error
if (error.response.status === 400 || error.response.status === 401) {
if (context) {
context.store.commit('setToken', null)
}
}
return Promise.reject(error)
})
Vue.use(VueAxios, axios)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment