index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // http封装库
  2. import axios from 'axios';
  3. import { getEnvConfig, removeStorage, storageKey, getMid, getUserInfo, appVersionCode } 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. let isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
  38. params = Object.assign(
  39. {
  40. baseInfo: {
  41. mid: getMid(),
  42. machineCode: getMid(),
  43. loginUid: (userInfo && userInfo.uid) || '',
  44. token: (userInfo && userInfo.accessToken) || '',
  45. appType: isMobile ? 2 : 1,
  46. appVersionCode,
  47. },
  48. },
  49. params
  50. );
  51. return instance
  52. .post(url, params, myConfig)
  53. .then((res) => {
  54. return res;
  55. })
  56. .catch((err) => {
  57. return err;
  58. });
  59. };
  60. export const getRequest = (url, params = {}, config = null) => {
  61. const myConfig = Object.assign({}, { params: Object.assign({}, params) });
  62. if (config) {
  63. Object.assign(myConfig, config);
  64. }
  65. return instance
  66. .get(url, myConfig)
  67. .then((res) => {
  68. return res;
  69. })
  70. .catch((err) => {
  71. return err;
  72. });
  73. };