zhaoxiaoqiang1
2026-01-04 f1d30d03186c79ca2cbcfe60d6d2ce7d73fba97b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/** axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios'
 
// const http = axios.create()
 
export default class BaseAxios {
  /**
   * constructor 构造函数
   * @param {Object} conf 实例全局配置,配置项基本同 defaultConf
   */
  constructor(conf = {}) {
    this.defaultConf = {
      // baseURL: process.env.VUE_APP_API_HOST,
      timeout: 60000,
      method: 'post',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      withCredentials: true,
      responseType: 'json'
    }
 
    this.specialParamsKeys = [
      'data',
      'method',
      'headers',
      'withCredentials',
      'responseType'
    ]
    this.init(conf)
  }
 
  /**
   * 初始化,合并配置
   * @param {Object} conf 全局配置
   */
  init(conf) {
    const { defaultConf } = this
    this.conf = Object.assign({}, { ...defaultConf }, { ...conf })
  }
 
  /**
   * post 请求处理
   * @param {String} api 接口地址
   * @param {Object|String} params 请求参数
   */
  post(api, params = {}, conf = {}) {
    return this.request(api, params, { method: 'post', ...conf })
  }
 
  /**
   * get 请求处理
   * @param {String} api 接口地址
   * @param {Object|String} params 请求参数
   */
  get(api, params = {}, conf = {}) {
    return this.request(api, params, { method: 'get', ...conf })
  }
 
  /**
   * mixParams 参数混入处理,可供实例后续扩展
   * @param {Object|String} params 请求参数
   */
  mixParams(params) {
    const { specialParamsKeys } = this
    if (typeof params === 'string') {
      params = { data: params }
    }
    if (typeof params === 'object') {
      // 若参数中包含配置信息,则不需要特殊处理(此时的实际参数为params的data字段)
      if (!Object.keys(params).some(key => specialParamsKeys.includes(key))) {
        params = { data: params }
      }
    }
    return params
  }
 
  /**
   * mixConf 合并配置项
   * @param {Object} conf 请求配置项
   * @param {Object} params 参数或包含参数的配置项 @example {data: {name: 'someone'}}
   */
  mixConf(conf = {}, params = {}) {
    return Object.assign(
      {},
      { ...this.conf },
      { ...conf },
      { ...this.mixParams(params) }
    )
  }
 
  /**
   * getUrl 获取请求url完整地址
   * @param {String} api请求地址
   * @param {Object} mixConf 混入后的请求配置
   */
  getUrl(api, mixConf) {
    const { method = 'post', baseURL = '', data = {} } = mixConf
    // 避免/符号重复
    let url = baseURL === '' ? baseURL : `${baseURL.replace(/\/+$/, '')}/`
 
    // 如果是完整http路径,则不用拼接baseURL前缀
    if (api.search(/^https?:\/\//) !== 0) {
      api = `${url}${api.replace(/^\/+/, '')}`
    }
    if (method.toLocaleLowerCase() === 'get') {
      const str = this.getUrlParams(data)
      api = api.includes('?') ? `${api}&${str}` : `${api}?${str}`
    }
    return api
  }
 
  /**
   * getUrlParams 拼接url字符串
   * @param {String} api 接口地址
   * @param {Object|String} params 请求参数
   */
  getUrlParams(params) {
    if (typeof params === 'object') {
      params = Object.keys(params).reduce((pre, curr) => {
        const val =
          typeof params[curr] === 'object'
            ? JSON.stringify(params[curr])
            : params[curr]
        pre = pre === '' ? pre : `${pre}&`
        pre = `${pre}${curr}=${val}`
        return pre
      }, '')
    }
    return params
  }
 
  /**
   * getParams 根据headers信息,
   * @param {Object} mixConf 请求配置项
   */
  getParams(mixConf) {
    let { data = {}, headers = {} } = mixConf
    Object.keys(headers).forEach(key => {
      if (key.toLocaleLowerCase() === 'content-type') {
        // json string
        if (
          headers[key].includes('application/json') &&
          typeof data !== 'string'
        ) {
          data = JSON.stringify(data)
        }
 
        // params
        if (headers[key].includes('application/x-www-form-urlencoded')) {
          data = this.getUrlParams(data)
        }
 
        // file
        if (
          headers[key].includes('multipart/form-data') &&
          !(data instanceof FormData)
        ) {
          const formData = new FormData()
          Object.keys(data).forEach(key => {
            formData.append(key, data[key])
          })
          data = formData
        }
      }
    })
    return data
  }
 
  /**
   * 请求统一入口
   * @param {String} api 接口地址
   * @param {Object|String} params 请求参数
   * @param {Object} conf 请求配置信息
   */
  request(api, params = {}, conf = {}) {
    const mixConf = this.mixConf(conf, params)
    const url = this.getUrl(api, mixConf)
    const data = this.getParams(mixConf)
    return this.axios({
      ...mixConf,
      url,
      data
    })
  }
 
  /**
   * 原始axios请求方法
   * @param {Object} conf 请求配置
   */
  axios(conf = {}) {
    return axios.create()(conf)
  }
}