loop_axios.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. "use strict";
  2. import axios from "axios";
  3. import { getCookie } from "@/utils/cookie";
  4. import { AUTH_TOKEN_FRONT, AUTH_TOKEN_END } from "@/common/Constant";
  5. import { getAllPromise } from "@/utils/tools";
  6. // 完整配置参考: https://github.com/axios/axios#request-config
  7. axios.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";
  8. let config = {
  9. baseURL: process.env.VUE_APP_BASE_API || process.env.apiUrl || "",
  10. timeout: 60 * 1000,
  11. withCredentials: false,
  12. crossDomain: true,
  13. transformRequest: [
  14. data => {
  15. if (!data || typeof data === "string") {
  16. return data;
  17. }
  18. if (data instanceof FormData) {
  19. return data;
  20. }
  21. // 对Blob对象进行处理
  22. let hasBlob = Object.values(data).some(it => {
  23. return it instanceof Blob;
  24. });
  25. if (!hasBlob) {
  26. return JSON.stringify(data);
  27. }
  28. const formData = new FormData();
  29. Object.entries(data).forEach(([key, value]) => {
  30. formData.append(key, value);
  31. });
  32. return formData;
  33. }
  34. ]
  35. };
  36. const _axios = axios.create(config);
  37. // 注册all方法,执行多个并发请求
  38. // 可传入Promise、包含Promise的数组、返回值为Promise的方法
  39. _axios.all = (...requsets) => {
  40. // 获取所有Promise对象
  41. let promiseList = getAllPromise(requsets);
  42. return new Promise((resolve, reject) => {
  43. axios.all(promiseList)
  44. .then(axios.spread((...response) => {
  45. // 两个请求现在都执行完成
  46. resolve(response);
  47. }))
  48. .catch(error => {
  49. reject(error);
  50. });
  51. });
  52. };
  53. _axios.interceptors.request.use(
  54. config => {
  55. const token = getCookie(AUTH_TOKEN_FRONT);
  56. config.headers.common[AUTH_TOKEN_END] = token;
  57. return config;
  58. },
  59. error => {
  60. return Promise.reject(error);
  61. }
  62. );
  63. // 拦截响应
  64. _axios.interceptors.response.use(
  65. response => {
  66. const success = response.status === 200; // && response.data.code === 0
  67. let message = "";
  68. return {
  69. data: response.data, // data
  70. success,
  71. message
  72. };
  73. },
  74. error => {
  75. return Promise.reject(error);
  76. }
  77. );
  78. export default {
  79. install: Vue => {
  80. Vue.$_loop_http = _axios;
  81. window.$_loop_http = _axios;
  82. Object.defineProperties(Vue.prototype, {
  83. $_loop_http: {
  84. get() {
  85. return _axios;
  86. }
  87. }
  88. });
  89. }
  90. };