api.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import Vue from 'vue'
  2. import axios from 'axios'
  3. import VueAxios from 'vue-axios'
  4. import router from './routes.js'
  5. Vue.use(VueAxios, axios)
  6. Vue.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  7. Vue.axios.defaults.headers.common['Content-Type'] = 'application/json'
  8. if (window.appConfig.APP_SUBDIRECTORY) {
  9. Vue.axios.defaults.baseURL = window.appConfig.subdirectory;
  10. }
  11. Vue.axios.interceptors.response.use(response => response, error => {
  12. // Return the error when we need to handle it at component level
  13. if( error.config.hasOwnProperty('returnError') && error.config.returnError === true ) {
  14. return Promise.reject(error);
  15. }
  16. // Return the error for form validation at component level
  17. if( error.response.status === 422 ) {
  18. return Promise.reject(error);
  19. }
  20. // Push to the login view and force the page to refresh to get a fresh CSRF token
  21. if ( error.response.status === 401 ) {
  22. router.push({ name: 'login', params: { forceRefresh: true } })
  23. throw new Vue.axios.Cancel();
  24. }
  25. if ( error.response.status === 407 ) {
  26. router.push({ name: 'genericError', params: { err: error.response, closable: false } })
  27. throw new Vue.axios.Cancel();
  28. }
  29. // we push to a specific or generic error view
  30. let routeName = 'genericError'
  31. // api calls are stateless so when user inactivity is detected
  32. // by the backend middleware it cannot logout the user directly
  33. // so it returns a 418 response.
  34. // We catch the 418 response and push the user to the autolock view
  35. if ( error.response.status === 418 ) routeName = 'autolock'
  36. if ( error.response.status === 404 ) routeName = '404'
  37. router.push({ name: routeName, params: { err: error.response } })
  38. throw new Vue.axios.Cancel();
  39. })