api.js 1.7 KB

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