api.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. redirect('/unauthorized')
  59. }
  60. })
  61. // Set baseURL to something different
  62. // api.setBaseURL('https://my_api.com')
  63. // Inject to context as $api
  64. inject('api', api)
  65. }