request.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import axios from 'axios'
  2. import { getChromeStorage } from '@/uilts/chromeExtension.js'
  3. import { baseAPIUrl, appVersionCode } from '@/http/configAPI.js'
  4. let userInfo = '';
  5. let storage_mid = ''
  6. // 创建axios实例
  7. export const service = axios.create({
  8. baseURL: baseAPIUrl, // api的base_url
  9. timeout: 240000, // 请求超时时间
  10. headers: {
  11. 'Content-Type': 'application/json', //指定消息格式
  12. 'Accept': 'application/json',
  13. },
  14. })
  15. function checkParams(config) {
  16. const { accessToken: token = '', uid = '' } = userInfo || {};
  17. const { mid } = storage_mid || {};
  18. if (config.method === 'get') {
  19. let { baseInfo = null } = config.params || {};
  20. let params = {
  21. ...config.params
  22. }
  23. let {pageSource} = params.params || {};
  24. if(pageSource) {
  25. delete params.params.pageSource;
  26. }
  27. if (!baseInfo || !baseInfo.token) {
  28. params['baseInfo'] = {
  29. token: token,
  30. mid,
  31. appVersionCode,
  32. loginUid: uid,
  33. uid,
  34. appType:1,
  35. machineCode: mid,
  36. pageSource: pageSource || ''
  37. }
  38. }
  39. config['params'] = params;
  40. }
  41. if (config.method === 'post') {
  42. let { baseInfo = null } = config.data || {};
  43. let data = {
  44. ...config.data
  45. }
  46. console.log('data', data)
  47. let {pageSource} = data.params || {};
  48. if(pageSource) {
  49. delete data.params.pageSource;
  50. }
  51. if (!baseInfo || !baseInfo.token) {
  52. data['baseInfo'] = {
  53. token: token,
  54. mid,
  55. appVersionCode,
  56. loginUid: uid,
  57. uid,
  58. appType:1,
  59. machineCode: mid,
  60. pageSource: pageSource || ''
  61. }
  62. }
  63. config['data'] = data;
  64. }
  65. return config
  66. }
  67. // request拦截器
  68. service.interceptors.request.use(async (config) => {
  69. if (!userInfo) {
  70. userInfo = await getChromeStorage('userInfo') || ''
  71. }
  72. if (!storage_mid) {
  73. storage_mid = await getChromeStorage('mid') || ''
  74. }
  75. return checkParams(config)
  76. }, error => {
  77. // Do something with request error
  78. console.log(error) // for debug
  79. Promise.reject(error)
  80. })
  81. // respone拦截器
  82. service.interceptors.response.use(
  83. response => {
  84. const res = response.data;
  85. return res
  86. },
  87. error => {
  88. console.log('err' + error) // for debug
  89. return Promise.reject(error)
  90. }
  91. )