Created
August 1, 2019 12:31
-
-
Save IgorDePaula/b9169f7069f00a8ccab91d3ef4f6718f to your computer and use it in GitHub Desktop.
http vue
This file contains hidden or 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' | |
export const http = axios.create({ baseURL: 'https://some-domain.com/api/'}) | |
const interceptors = (http) => { | |
http.interceptors.request.use((config) => { | |
// loading start | |
}, (error) => { | |
loadingInstance.close() | |
return Promise.reject(error) | |
}) | |
// Add a response interceptor | |
http.interceptors.response.use((response) => { | |
if (response.headers.hasOwnProperty('newtoken')) { | |
setToken(response.headers.newtoken) | |
} | |
// loading end | |
return response | |
}, (error) => { | |
if (error.response.data.hasOwnProperty('error')) { | |
const errorMessage = error.response.data.error | |
if (errorMessage === 'token_expired' || errorMessage === 'token_invalid') { | |
router.push('auth') | |
} | |
} | |
// loading end | |
return Promise.reject(error) | |
}) | |
} | |
export function setToken (token) { | |
http.defaults.headers.common.Authorization = `Bearer ${token}` | |
} | |
export default function install (Vue) { | |
interceptors(http) | |
Vue.prototype.$http = http | |
} |
This file contains hidden or 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 http from './http' | |
Vue.use(http) | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment