httpParamsFormatting.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. // 执行响应脚本
  38. if (newCustomConfig.responseScript) {
  39. // eslint-disable-next-line no-new-func
  40. const getResp = new Function('resp', newCustomConfig.responseScript)
  41. const res = getResp(resp)
  42. return Promise.resolve(res)
  43. } else {
  44. return Promise.resolve(resp)
  45. }
  46. })
  47. const body = newCustomConfig?.body.replace(/: ,/g, ':undefined,').replace(/, }/g, ',undefined}')
  48. /** 发送请求 **/
  49. return new Promise((resolve, reject) => {
  50. instance({
  51. method: newCustomConfig.method,
  52. url: newCustomConfig.url,
  53. params: newCustomConfig.params,
  54. // params 序列化操作
  55. paramsSerializer: (params) => {
  56. return Object.keys(params)
  57. .map(key => {
  58. if (Array.isArray(params[key])) {
  59. return params[key].map(value => `${key}=${value}`).join('&')
  60. } else {
  61. return `${key}=${params[key]}`
  62. }
  63. })
  64. .join('&')
  65. },
  66. data: newCustomConfig.method === 'post' ? body : undefined
  67. }).then(response => {
  68. resolve(response)
  69. }).catch(error => {
  70. reject(error)
  71. })
  72. })
  73. }
  74. // 动态替换url后面参数的值
  75. function replaceUrlParam (url, paramName, paramValue) {
  76. const regex = new RegExp(`([?&])${paramName}=.*?(&|$)`, 'i')
  77. const separator = url.indexOf('?') !== -1 ? '&' : '?'
  78. if (url.match(regex)) {
  79. return url.replace(regex, `$1${paramName}=${paramValue}$2`)
  80. } else {
  81. return `${url}${separator}${paramName}=${paramValue}`
  82. }
  83. }
  84. // 将参数的值替换掉其他配置中对应属性的值
  85. function replaceParams (customConfig) {
  86. const newConfig = cloneDeep(customConfig)
  87. newConfig.url = evalStrFunc(newConfig.paramsList, newConfig.url)
  88. newConfig.headers = evalArrFunc(newConfig.paramsList, newConfig.headers)
  89. newConfig.params = evalArrFunc(newConfig.paramsList, newConfig.params)
  90. newConfig.body = evalStrFunc(newConfig.paramsList, newConfig.body)
  91. return newConfig
  92. }
  93. function evalStrFunc (paramsList, string) {
  94. // 取name作为变量名, value作为变量值 { name: '站三', token: '123'}
  95. const params = paramsList.reduce((acc, cur) => {
  96. acc[cur.name] = cur.value
  97. return acc
  98. }, {})
  99. // 将url中 ${xxx} 替换成 ${params.xxx}
  100. const str = string.replace(/\$\{(\w+)\}/g, (match, p1) => {
  101. return '${params.' + p1 + '}'
  102. })
  103. const transformStr = ''
  104. // 将字符串中的${}替换为变量, 使用eval执行
  105. eval('transformStr = `' + str + '`')
  106. return transformStr
  107. }
  108. function evalArrFunc (paramsList, arr) {
  109. // 取name作为变量名, value作为变量值 { name: '站三', token: '123'}
  110. const params = paramsList.reduce((acc, cur) => {
  111. acc[cur.name] = cur.value
  112. return acc
  113. }, {})
  114. // 取name作为变量名, value作为变量值 { _name: '${name}', _token: '${token}'}
  115. const paramsListObj = arr.reduce((acc, cur) => {
  116. if (acc[cur.key]) {
  117. if (Array.isArray(acc[cur.key])) {
  118. acc[cur.key].push(cur.value)
  119. } else {
  120. acc[cur.key] = [acc[cur.key], cur.value]
  121. }
  122. } else {
  123. acc[cur.key] = cur.value
  124. }
  125. return acc
  126. }, {})
  127. // 转成字符串
  128. const paramsListStr = JSON.stringify(paramsListObj)
  129. // 将url中 ${xxx} 替换成 ${params.xxx}
  130. const str = paramsListStr.replace(/\$\{(\w+)\}/g, (match, p1) => {
  131. return '${params.' + p1 + '}'
  132. })
  133. const transformStr = ''
  134. // 将字符串中的${}替换为变量, 使用eval执行
  135. eval('transformStr = `' + str + '`')
  136. const obj = JSON.parse(transformStr)
  137. return obj
  138. }