index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import axios from 'axios';
  2. import Vue from 'vue';
  3. const instance = axios.create(config);
  4. // 3. 配置信息
  5. let config = {
  6. // 每次请求的协议、IP地址。 设置该配置后,每次请求路径都可以使用相对路径,例如"/admin/login"
  7. // baseURL: "http://127.0.0.1:5590",
  8. // 请求超时时间
  9. timeout: 0,
  10. // 每次请求携带cookie
  11. withCredentials: true,
  12. };
  13. //请求拦截,后期可能会用到,先注册在此
  14. instance.interceptors.request.use(
  15. function(config) {
  16. Vue.prototype.$loading.show();
  17. let token = localStorage.getItem('token');
  18. // let proxy_url = 'http://121.37.173.82:82'; //打包上线时请改用此处
  19. let proxy_url = process.env.VUE_APP_BASE_URL//打包上线时请改用此处
  20. // let proxy_url = '/proxy'//打包上线时此处请注释掉
  21. config.url = proxy_url + config.url;
  22. // 在发送请求之前做些什么,例如加入token
  23. config.headers['Authorization'] = token;
  24. return config;
  25. },
  26. function(error) {
  27. // 对请求错误做些什么
  28. return Promise.reject(error);
  29. }
  30. );
  31. // 2. 响应拦截
  32. instance.interceptors.response.use(
  33. (res) => {
  34. Vue.prototype.$loading.hide();
  35. if (res.status == 200) {
  36. if (res.data.code == 200) {
  37. return res.data;
  38. } else {
  39. //若code 非 200
  40. if (res.data.code == 401) {
  41. localStorage.removeItem('token');
  42. return location.reload();
  43. }
  44. Vue.prototype.$Message.error(res.data.msg || '未知错误');
  45. return res.data || res;
  46. }
  47. } else {
  48. return Vue.prototype.$Message.error('请求超时');
  49. }
  50. },
  51. // 对于错误响应的处理
  52. (err) => {
  53. Vue.prototype.$Notice.error({ title: '请求失败', desc: err });
  54. Vue.prototype.$loading.hide();
  55. return err;
  56. }
  57. );
  58. export default instance;