index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // http封装库
  2. import axios from 'axios';
  3. import { getEnvConfig, removeStorage, storageKey, getMid, getUserInfo, appVersionCode, appType } from '../utils/help';
  4. // 测试数据(需手动开启关闭)
  5. // import '../mockjs/index';
  6. // axios config
  7. const { host } = getEnvConfig();
  8. const instance = axios.create({
  9. baseURL: host,
  10. timeout: 240000,
  11. headers: {
  12. 'content-type': 'application/json',
  13. Accept: 'application/json',
  14. },
  15. });
  16. // 响应拦截器
  17. instance.interceptors.response.use(
  18. (res) => {
  19. if (res.data.code === -107) {
  20. // token失效
  21. removeStorage(storageKey.userInfo);
  22. location.reload();
  23. } else {
  24. return res.data;
  25. }
  26. },
  27. function (err) {
  28. return Promise.reject(err);
  29. }
  30. );
  31. export const postRequest = (url, params = {}, config = null) => {
  32. const myConfig = {};
  33. const userInfo = getUserInfo();
  34. if (config) {
  35. Object.assign(myConfig, config);
  36. }
  37. params = Object.assign(
  38. {
  39. baseInfo: {
  40. mid: getMid(),
  41. machineCode: getMid(),
  42. loginUid: (userInfo && userInfo.uid) || '',
  43. token: (userInfo && userInfo.accessToken) || '',
  44. appType,
  45. appVersionCode,
  46. },
  47. },
  48. params
  49. );
  50. return instance
  51. .post(url, params, myConfig)
  52. .then((res) => {
  53. return res;
  54. })
  55. .catch((err) => {
  56. return err;
  57. });
  58. };
  59. export const getRequest = (url, params = {}, config = null) => {
  60. const myConfig = Object.assign({}, { params: Object.assign({}, params) });
  61. if (config) {
  62. Object.assign(myConfig, config);
  63. }
  64. return instance
  65. .get(url, myConfig)
  66. .then((res) => {
  67. return res;
  68. })
  69. .catch((err) => {
  70. return err;
  71. });
  72. };