Created
January 22, 2018 16:45
-
-
Save Phunky/a98cab87f4c873bc30c7d026db507384 to your computer and use it in GitHub Desktop.
Example axios wrapping I used for my own APIs
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' | |
// Instance | |
let http = axios.create({ | |
baseURL: process.env.API_URL, | |
timeout: process.env.API_TIMEOUT, | |
headers: { | |
} | |
}) | |
// Add a request interceptor | |
http.interceptors.request.use(function (config) { | |
config.headers.common['Authorization'] = `Bearer ${store.getters.session.token}` | |
return config | |
}, function (error) { | |
// Do something with request error | |
return Promise.reject(error) | |
}) | |
// Add a response interceptor | |
http.interceptors.response.use(function (response) { | |
return response | |
}, function (error) { | |
if (error.response.status === 401 && store.getters.session.token) { | |
store.dispatch('logout', false) | |
} | |
return Promise.reject(error.response) | |
}) | |
export default http |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment