httpParamsFormatting.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import axios from 'axios'
  2. // import { Loading, Message } from 'element-ui'
  3. // import _ from 'lodash'
  4. import cloneDeep from 'lodash/cloneDeep'
  5. export default function axiosFormatting (customConfig) {
  6. const newCustomConfig = replaceParams(customConfig)
  7. // 将请求头和请求参数的值转化为对象形式
  8. const httpConfig = {
  9. timeout: 1000 * 30,
  10. baseURL: '',
  11. headers: { 'Content-Type': 'application/json', ...newCustomConfig.headers }
  12. }
  13. // let loadingInstance = null // 加载全局的loading
  14. const instance = axios.create(httpConfig)
  15. /** 添加请求拦截器 **/
  16. instance.interceptors.request.use(config => {
  17. /**
  18. * 在这里:可以根据业务需求可以在发送请求之前做些什么。
  19. * config.headers['token'] = sessionStorage.getItem('token') || ''
  20. */
  21. // 执行请求脚本
  22. // https://mock.presstime.cn/mock/64bf8a00ce1b0ea640809069/test_copy_copy_copy/httpData?token=123&ss=ss
  23. const req = { ...config, url: {} }
  24. eval(newCustomConfig.requestScript)
  25. for (const key in req.url) {
  26. newCustomConfig.url = replaceUrlParam(newCustomConfig.url, key, req.url[key])
  27. }
  28. config = { ...config, ...req, url: newCustomConfig.url }
  29. return config
  30. }, error => {
  31. // 对请求错误做些什么
  32. return Promise.reject(error)
  33. })
  34. /** 添加响应拦截器 **/
  35. instance.interceptors.response.use(response => {
  36. const resp = response.data
  37. console.log('resp', resp)
  38. // 执行响应脚本
  39. if (newCustomConfig.responseScript) {
  40. // eslint-disable-next-line no-new-func
  41. const getResp = new Function('resp', newCustomConfig.responseScript)
  42. const res = getResp(resp)
  43. console.log('resp', res)
  44. return Promise.resolve(res)
  45. } else {
  46. return Promise.resolve(resp)
  47. }
  48. })
  49. const body = newCustomConfig?.body.replace(/: ,/g, ':undefined,').replace(/, }/g, ',undefined}')
  50. /** 发送请求 **/
  51. return new Promise((resolve, reject) => {
  52. instance({
  53. method: newCustomConfig.method,
  54. url: newCustomConfig.url,
  55. params: newCustomConfig.params,
  56. data: newCustomConfig.method === 'post' ? body : undefined
  57. }).then(response => {
  58. resolve(response)
  59. }).catch(error => {
  60. reject(error)
  61. })
  62. })
  63. }
  64. // 动态替换url后面参数的值
  65. function replaceUrlParam (url, paramName, paramValue) {
  66. const regex = new RegExp(`([?&])${paramName}=.*?(&|$)`, 'i')
  67. const separator = url.indexOf('?') !== -1 ? '&' : '?'
  68. if (url.match(regex)) {
  69. return url.replace(regex, `$1${paramName}=${paramValue}$2`)
  70. } else {
  71. return `${url}${separator}${paramName}=${paramValue}`
  72. }
  73. }
  74. // 将参数的值替换掉其他配置中对应属性的值
  75. function replaceParams (customConfig) {
  76. const newConfig = cloneDeep(customConfig)
  77. newConfig.url = evalStrFunc(newConfig.paramsList, newConfig.url)
  78. newConfig.headers = evalArrFunc(newConfig.paramsList, newConfig.headers)
  79. newConfig.params = evalArrFunc(newConfig.paramsList, newConfig.params)
  80. newConfig.body = evalStrFunc(newConfig.paramsList, newConfig.body)
  81. return newConfig
  82. }
  83. function evalStrFunc (paramsList, string) {
  84. // 取name作为变量名, value作为变量值 { name: '站三', token: '123'}
  85. const params = paramsList.reduce((acc, cur) => {
  86. acc[cur.name] = cur.value
  87. return acc
  88. }, {})
  89. // 将url中 ${xxx} 替换成 ${params.xxx}
  90. const str = string.replace(/\$\{(\w+)\}/g, (match, p1) => {
  91. return '${params.' + p1 + '}'
  92. })
  93. const transformStr = ''
  94. // 将字符串中的${}替换为变量, 使用eval执行
  95. eval('transformStr = `' + str + '`')
  96. return transformStr
  97. }
  98. function evalArrFunc (paramsList, arr) {
  99. // 取name作为变量名, value作为变量值 { name: '站三', token: '123'}
  100. const params = paramsList.reduce((acc, cur) => {
  101. acc[cur.name] = cur.value
  102. return acc
  103. }, {})
  104. // 取name作为变量名, value作为变量值 { _name: '${name}', _token: '${token}'}
  105. const paramsListObj = arr.reduce((acc, cur) => {
  106. acc[cur.key] = cur.value
  107. return acc
  108. }, {})
  109. // 转成字符串
  110. const paramsListStr = JSON.stringify(paramsListObj)
  111. // 将url中 ${xxx} 替换成 ${params.xxx}
  112. const str = paramsListStr.replace(/\$\{(\w+)\}/g, (match, p1) => {
  113. return '${params.' + p1 + '}'
  114. })
  115. const transformStr = ''
  116. // 将字符串中的${}替换为变量, 使用eval执行
  117. eval('transformStr = `' + str + '`')
  118. const obj = JSON.parse(transformStr)
  119. return obj
  120. }