http.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import axios from 'axios';
  2. import qs from 'qs';
  3. /* eslint-disable */
  4. let baseUrl = process.env.VUE_APP_BASE_URL;
  5. const axiosInstance = axios.create({
  6. baseURL: baseUrl
  7. });
  8. axiosInstance.interceptors.request.use(
  9. function (config) {
  10. config.headers = config.headers || {};
  11. let token = localStorage.getItem('dianjinToken');
  12. if (token) {
  13. config.headers['Authorization'] = 'Bearer ' + token;
  14. }
  15. return config;
  16. },
  17. function (error) {
  18. return Promise.reject(error);
  19. }
  20. );
  21. axiosInstance.interceptors.response.use(
  22. function (response) {
  23. return response;
  24. },
  25. function (error) {
  26. let errorData = {};
  27. if (!error.response) {
  28. errorData = {
  29. error: '网络错误,请检查网络链接'
  30. };
  31. } else {
  32. errorData = error.response.data;
  33. // if (401 === error.response.status) {
  34. // if (router.currentRoute.name !== 'login') {
  35. // router.replace({
  36. // name: 'login',
  37. // params: {
  38. // from: router.currentRoute.name
  39. // }
  40. // });
  41. // } else {
  42. // }
  43. // }
  44. }
  45. if (typeof errorData != 'object') {
  46. errorData = {
  47. error: '请求失败' + error.response.status
  48. };
  49. }
  50. return Promise.reject(errorData);
  51. }
  52. );
  53. const http = {
  54. get(url, params) {
  55. params = params || {};
  56. return new Promise((resolve, reject) => {
  57. axiosInstance
  58. .get(
  59. url,
  60. {
  61. params: params
  62. },
  63. {
  64. withCredentials: true
  65. }
  66. )
  67. .then(res => {
  68. resolve(res.data);
  69. })
  70. .catch(e => {
  71. reject(e);
  72. });
  73. });
  74. },
  75. post(url, body, options) {
  76. options = options || {};
  77. body = body || {};
  78. if (!(body instanceof FormData)) {
  79. if (options.body !== 'json') {
  80. body = qs.stringify(body);
  81. }
  82. }
  83. return new Promise((resolve, reject) => {
  84. axiosInstance
  85. .post(url, body, {
  86. withCredentials: true
  87. })
  88. .then(res => {
  89. resolve(res.data);
  90. })
  91. .catch(e => {
  92. reject(e);
  93. });
  94. });
  95. }
  96. };
  97. export default {
  98. axios: axiosInstance,
  99. http: http,
  100. install(app, options) {
  101. app.config.globalProperties.$baseUrl = baseUrl;
  102. app.config.globalProperties.$axios = axiosInstance;
  103. app.config.globalProperties.$http = http;
  104. }
  105. };