http.js 3.9 KB
/*
 * @Author: limin
 * @Date: 2018-06-25 10:28:18
 * @Last Modified by: huyue
 * @Last Modified time: 2021-07-16 18:02:05
 */
import util from './util'
import axios from 'axios'
import qs from 'qs'
import WhiteUrlManager from './whiteUrlManager' // 导入白名单管理器
function Http(options = {}) {
  this.service = axios.create({
    withCredentials: true,
    method: 'POST'
  })
  const { response = {}, request = {}, headers = {}, alert, sign, signWay = 'sha1', secret } = options
  this.customer = {
    response,
    alert,
    sign,
    secret,
    signWay,
    sessionId: headers.token
  }
  const { baseURL, timeout = 3000, withCredentials = true, responseType = 'json' } = request
  Object.assign(this.service.defaults, { headers: Object.assign({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, headers) }, { baseURL, timeout, withCredentials, responseType })
  return this.create()
}
Http.prototype.create = function () {
  this.service.interceptors.request.use(
    async config => {
      let { data = {}, sign = true, noSignAttr = [], noSessionId = false } = config
      // 获取白名单并检查接口
      const whiteUrl = await WhiteUrlManager.getWhiteUrls()

      if (whiteUrl.includes(data?.method)) {
        data.sdctag = true
      }
      if (!noSessionId) {
        data.sessionId = this.customer.sessionId || data.sessionId
      }
      if (sign) {
        let _configSign = this.customer.sign || {}
        data = util.createSign(Object.assign({}, _configSign, data), this.customer.secret, noSignAttr, this.customer.signWay)
      }
      const method = config.method.toLowerCase()
      if (method == 'get') {
        // config.data = data
        config.params = data
      } else if (method == 'post') {
        // 将 sdctag
        if (data.sdctag) {
          config.params = { ...config.params, sdctag: data.sdctag }
        }
        if (config.headers['Content-Type'] == 'multipart/form-data') {
          config.data = util.appendFormData(data)
        } else if (config.headers['Content-Type'] == 'application/json') {
          config.data = data
        } else {
          config.data = qs.stringify(data)
        }
      }
      return config
    },
    error => Promise.reject(error)
  )
  this.service.interceptors.response.use(
    ({ data: res, config: { returnAll } }) => {
      const {
        response: { code_key, errId = 'errId', code_success_value = '0', data_key = 'data', errId_logout_value, logout_function = 'logout' },
        alert
      } = this.customer
      // if (returnAll || !alert) {
      //   return res
      // }
      let codekey = Array.isArray(code_key) ? code_key.find(key => res.hasOwnProperty(key)) : code_key
      let code = res[codekey]
      let errValue = res[errId]
      if (returnAll || !alert) {
        if ((code && code == errId_logout_value) || (errValue && errValue == errId_logout_value)) {
          logout(logout_function)
        }
        return res
      }
      // 特殊的code处理,可以增加
      switch (code + '') {
        case code_success_value + '':
          break
        case errId_logout_value + '':
          logout(logout_function)
          break
        default:
          if (errValue && errValue == errId_logout_value) {
            return logout(logout_function)
          }
          alert(res.message || res.msg || '出错了,请联系管理员')
          break
      }
      return res[data_key]
    },
    error => {
      const { alert } = this.customer
      alert && alert(error.message || '出错了,请联系管理员')
      // 返回接口返回的错误信息
      return Promise.reject(error)
    }
  )
  this.service.axios = axios
  return this.service
}
function logout(logout_function) {
  WhiteUrlManager.clearCache()
  if (window[logout_function]) {
    window[logout_function](window.location.href)
    return
  }
  window.history.pushState({ page: window.location.href }, '', '/login')
}
export default Http