httpParamsFormatting.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. data: newCustomConfig.method === 'post' ? body : undefined
  55. }).then(response => {
  56. resolve(response)
  57. }).catch(error => {
  58. reject(error)
  59. })
  60. })
  61. }
  62. // 动态替换url后面参数的值
  63. function replaceUrlParam (url, paramName, paramValue) {
  64. const regex = new RegExp(`([?&])${paramName}=.*?(&|$)`, 'i')
  65. const separator = url.indexOf('?') !== -1 ? '&' : '?'
  66. if (url.match(regex)) {
  67. return url.replace(regex, `$1${paramName}=${paramValue}$2`)
  68. } else {
  69. return `${url}${separator}${paramName}=${paramValue}`
  70. }
  71. }
  72. // 将参数的值替换掉其他配置中对应属性的值
  73. function replaceParams (customConfig) {
  74. const newConfig = cloneDeep(customConfig)
  75. newConfig.url = evalStrFunc(newConfig.paramsList, newConfig.url)
  76. newConfig.headers = evalArrFunc(newConfig.paramsList, newConfig.headers)
  77. newConfig.params = evalArrFunc(newConfig.paramsList, newConfig.params)
  78. newConfig.body = evalStrFunc(newConfig.paramsList, newConfig.body)
  79. return newConfig
  80. }
  81. function evalStrFunc (paramsList, string) {
  82. // 取name作为变量名, value作为变量值 { name: '站三', token: '123'}
  83. const params = paramsList.reduce((acc, cur) => {
  84. acc[cur.name] = cur.value
  85. return acc
  86. }, {})
  87. // 将url中 ${xxx} 替换成 ${params.xxx}
  88. const str = string.replace(/\$\{(\w+)\}/g, (match, p1) => {
  89. return '${params.' + p1 + '}'
  90. })
  91. const transformStr = ''
  92. // 将字符串中的${}替换为变量, 使用eval执行
  93. eval('transformStr = `' + str + '`')
  94. return transformStr
  95. }
  96. function evalArrFunc (paramsList, arr) {
  97. // 取name作为变量名, value作为变量值 { name: '站三', token: '123'}
  98. const params = paramsList.reduce((acc, cur) => {
  99. acc[cur.name] = cur.value
  100. return acc
  101. }, {})
  102. // 取name作为变量名, value作为变量值 { _name: '${name}', _token: '${token}'}
  103. const paramsListObj = arr.reduce((acc, cur) => {
  104. acc[cur.key] = cur.value
  105. return acc
  106. }, {})
  107. // 转成字符串
  108. const paramsListStr = JSON.stringify(paramsListObj)
  109. // 将url中 ${xxx} 替换成 ${params.xxx}
  110. const str = paramsListStr.replace(/\$\{(\w+)\}/g, (match, p1) => {
  111. return '${params.' + p1 + '}'
  112. })
  113. const transformStr = ''
  114. // 将字符串中的${}替换为变量, 使用eval执行
  115. eval('transformStr = `' + str + '`')
  116. const obj = JSON.parse(transformStr)
  117. return obj
  118. }