api.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. export default function ({ $axios, redirect, app, store }, inject) {
  2. // $axios.onRequest(config => {
  3. // if(store.state.token){
  4. // config.headers['Authorization'] = 'Bearer ' + store.state.token;
  5. // }
  6. // return config;
  7. // });
  8. //
  9. // $axios.setHeader('Content-Type', 'application/json');
  10. //
  11. // $axios.onResponse(response =>{
  12. // console.log("response", response);
  13. // if(response.status === 401){
  14. // app.$cookies.removeAll();
  15. // store.commit('saveToken', null);
  16. // store.commit('saveUser', {});
  17. // this.$message({
  18. // showClose: true,
  19. // message: '未授权,请先登录',
  20. // type: 'warning'
  21. // });
  22. // }
  23. //
  24. // });
  25. // Create a custom axios instance
  26. const api = $axios.create({
  27. // headers: {
  28. // common: {
  29. // Accept: 'text/plain, */*'
  30. // }
  31. // },
  32. baseURL: '/api',
  33. timeout: 10000,
  34. withCredentials: true
  35. });
  36. api.onRequest(config => {
  37. if(store.state.token){
  38. config.headers['authorization'] = 'Bearer ' + store.state.token;
  39. }else{
  40. delete config.headers['authorization'];
  41. }
  42. return config;
  43. });
  44. api.setHeader('Content-Type', 'application/json');
  45. api.onResponse(response =>{
  46. if(response.status === 401){
  47. app.$cookies.removeAll();
  48. store.commit('saveToken', null);
  49. store.commit('saveUser', {});
  50. redirect('/unauthorized');
  51. }
  52. });
  53. api.onError(error => {
  54. if(error.response.status === 401) {
  55. app.$cookies.removeAll();
  56. store.commit('saveToken', null);
  57. store.commit('saveUser', {});
  58. console.log('here')
  59. redirect('/unauthorized');
  60. }
  61. });
  62. // Set baseURL to something different
  63. // api.setBaseURL('https://my_api.com')
  64. // Inject to context as $api
  65. inject('api', api)
  66. }