httpParamsFormatting.js 4.8 KB

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