api.js 978 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. export default function ({ $axios, redirect, app, store }, inject) {
  2. $axios.onRequest(config => {
  3. if(store.state.token){
  4. config.headers.common['Authorization'] = 'Bearer ' + store.state.token;
  5. }
  6. return config;
  7. });
  8. $axios.setHeader('Content-Type', 'application/json');
  9. $axios.onResponse(response =>{
  10. if(response.status === 401){
  11. app.$cookies.removeAll();
  12. store.commit('setToken', null);
  13. store.commit('setUser', {});
  14. this.$message({
  15. showClose: true,
  16. message: '未授权,请先登录',
  17. type: 'warning'
  18. });
  19. }
  20. });
  21. // Create a custom axios instance
  22. const api = $axios.create({
  23. // headers: {
  24. // common: {
  25. // Accept: 'text/plain, */*'
  26. // }
  27. // },
  28. baseURL: '/api',
  29. timeout: 10000,
  30. withCredentials: true
  31. });
  32. // Set baseURL to something different
  33. // api.setBaseURL('https://my_api.com')
  34. // Inject to context as $api
  35. inject('api', api)
  36. }