api.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 = 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. store.commit('saveToken', null)
  48. store.commit('saveUser', {})
  49. redirect('/unauthorized')
  50. }
  51. })
  52. api.onError(error => {
  53. if (error.response.status === 401) {
  54. store.commit('saveToken', null)
  55. store.commit('saveUser', {})
  56. redirect('/unauthorized')
  57. }
  58. })
  59. // Set baseURL to something different
  60. // api.setBaseURL('https://my_api.com')
  61. // Inject to context as $api
  62. inject('api', api)
  63. }