axios.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // import { Loading } from 'element-ui';
  2. import { checkUrl } from "@/datav/utils/utils";
  3. import axios from "axios";
  4. window.$glob = {
  5. url: "",
  6. params: {},
  7. query: {},
  8. header: {},
  9. };
  10. function getGlobParams() {
  11. var query = window.location.search.substring(1);
  12. query = query.split("&");
  13. query.forEach((ele) => {
  14. var pair = ele.split("=");
  15. window.$glob.params[pair[0]] = pair[1];
  16. });
  17. }
  18. getGlobParams();
  19. axios.defaults.timeout = 10000;
  20. //返回其他状态吗
  21. axios.defaults.validateStatus = function (status) {
  22. return status >= 200 && status <= 500; // 默认的
  23. };
  24. //跨域请求,允许保存cookie
  25. // let loadingInstance = '';
  26. axios.defaults.withCredentials = true;
  27. axios.interceptors.request.use(
  28. (config) => {
  29. // loadingInstance = Loading.service({
  30. // text: '拼命加载中',
  31. // background: 'rgba(0,0,0,0)',
  32. // spinner: 'el-icon-loading'
  33. // });
  34. if (!checkUrl(config.url)) config.url = window.$glob.url + config.url;
  35. let header = window.$glob.header || {};
  36. config.headers = Object.assign(config.headers, header);
  37. let data = window.$glob.query || {};
  38. let key;
  39. if (config.method == "get") {
  40. key = "params";
  41. } else if (config.method == "post") {
  42. key = "data";
  43. }
  44. if (typeof config[key] === "object") {
  45. config[key] = Object.assign(config[key] || {}, data);
  46. }
  47. return config;
  48. },
  49. (error) => {
  50. return Promise.reject(error);
  51. }
  52. );
  53. //HTTPrequest拦截
  54. axios.interceptors.response.use(
  55. (config) => {
  56. // loadingInstance.close();
  57. return config;
  58. },
  59. (error) => {
  60. // loadingInstance.close();
  61. return Promise.reject(new Error(error));
  62. }
  63. );
  64. export default axios;