Created
February 25, 2020 10:12
-
-
Save garethredfern/8e64041b7b15767c1c7cb635ac63eb7e to your computer and use it in GitHub Desktop.
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
/* | |
* This is the initial API interface | |
* we set the base URL for the API | |
* store the token in local storage | |
* append the token to all requests | |
? Both request & response are logged to the console. | |
? Should we use a cookie instead of local storage? | |
! Remove the console logs for production. | |
*/ | |
import axios from "axios"; | |
import router from "../router"; | |
import store from "../store/store"; | |
export const apiClient = axios.create({ | |
baseURL: process.env.VUE_APP_API_URL, | |
withCredentials: false, // This is the default | |
}); | |
/* | |
* Add a request interceptor | |
@param config | |
*/ | |
apiClient.interceptors.request.use( | |
function(config) { | |
const token = window.localStorage.getItem("token"); | |
if (token != null) { | |
config.headers.Authorization = `Bearer ${token}`; | |
} | |
return config; | |
}, | |
function(error) { | |
return Promise.reject(error.response); | |
} | |
); | |
/* | |
* Add a response interceptor | |
*/ | |
apiClient.interceptors.response.use( | |
response => { | |
return response; | |
}, | |
function(error) { | |
if (error.response.status === 401) { | |
store.dispatch("auth/logout"); | |
} | |
if (error.response.status === 403) { | |
router.push("/403"); | |
} | |
if (error.response.status === 503) { | |
router.push("/503"); | |
} | |
// TODO Remove for go live | |
// eslint-disable-next-line no-console | |
console.log(error); | |
//console.log(error.message); | |
return Promise.reject(error.response); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment