小程序中的axios封装请求

import axios from 'axios'
import store from '@/store'
import { baseConfig } from '../../base.config'
import { refreshtokenApi } from '../pages/login/api'
import qs from 'qs'
let axiosPromiseArr = []

// 做了一个适配,在axios的外面,套了一个wx.request用于适配小程序
axios.defaults.adapter = function(config) {
  return new Promise((resolve, reject) => {
    var settle = require('axios/lib/core/settle')  // settle操作,会额外判断是否是合理的status状态
    var buildURL = require('axios/lib/helpers/buildURL') // url拼接方法
    wx.request({
      method: config.method.toUpperCase(),
      url:
        config.baseURL +
        buildURL(config.url, config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete: function complete(response) {
        response = {
          data: response.data,
          status: response.statusCode,
          errMsg: response.errMsg,
          header: response.header,
          config: config
        }
        settle(resolve, reject, response)
      }
    })
  })
}
const httpRequest = axios.create({
  withCredentials: true,
  crossDomain: true,
  baseURL: baseConfig.baseURL,
  timeout: 6000
})

httpRequest.setToken = token => {
  httpRequest.defaults.headers.Authorization = token
  store.commit('SET_TOKEN', token)
}
const getDataType = obj => {
  let rawType = Object.prototype.toString.apply(obj)
  let len = rawType.length - 1
  return rawType.substring(8, len)
}
// 是否正在刷新的标记
let isRefreshing = false
// 重试队列,每一项将是一个待执行的函数形式
let requests = []

const instanceConf = config => {
  config.cancelToken = new axios.CancelToken(cancel => {
    axiosPromiseArr.push({ cancel })
  })
  // token
  if (store.state.token) {
    config.headers['Authorization'] = store.state.token
  }
  if (
    config.method === 'post' &&
    config.data &&
    config.headers['Content-Type'] !== 'application/json' &&
    config.headers['Content-Type'] !== 'multipart/form-data'
  ) {
    if (getDataType(config.data) === 'Object') {
      config.data = qs.stringify(config.data)
    }
  }
  config.headers['ClientType'] = 'MINI'
  config.headers['X-AUTHORIZATION'] = store.state.token
  config.headers['R-AUTHORIZATION'] = store.state.refreshToken
  config.headers['X-APPID'] = '1012'
  config.headers['X-CLIENT-TYPE'] = 'MINI'
  config.headers['X-PROJECT-UUID'] = store.state.projectUuid
  return config
}
/**
 * 重定向
 */
const routerRedirect = () => {
  // Message.warning(`身份过期,请重新登录!`)
  uni.redirectTo({
    url: '/pages/login/Login'
  })
}

// 请求拦截
httpRequest.interceptors.request.use(instanceConf, function(error) {
  return Promise.reject(error)
})

// 响应拦截
httpRequest.interceptors.response.use(
  async function(response) {
    let code = (response && response.data && response.data.code) || '无code'
    let whiteList = [0, 200]
    if (whiteList.includes(code)) {
      return response.data
    } else if (code == 402) {
      if (!isRefreshing) {
        isRefreshing = true
        try {
          const {
            data: { token }
          } = await refreshtokenApi()
          if (token) {
            httpRequest.setToken(token)
            response.config.headers.Authorization = token
            // 已经刷新了token,将所有队列中的请求进行重试
            requests.forEach(cb => cb(token))
            requests = []
            return httpRequest(instanceConf(response.config))
          }
        } catch (error) {
          //刷新时候直接判断token 不用判断code
          console.error('refreshtoken error =>', error)
          routerRedirect()
        } finally {
          isRefreshing = false
        }
      } else {
        // 正在刷新token,将返回一个未执行resolve的promise
        return new Promise(resolve => {
          // 将resolve放进队列,用一个函数形式来保存,等token刷新后直接执行
          requests.push(token => {
            response.config.headers.Authorization = token
            resolve(httpRequest(instanceConf(response.config)))
          })
        })
      }
    } else if (
      [
        401,
        10005,
        500000,
        500001,
        500002,
        500003,
        500004,
        600000,
        600001,
        150000,
        100001,
        20003
      ].includes(code)
    ) {
      routerRedirect()
    }
    return Promise.reject(response.data)
  },
  function(error) {
    console.log(error.response, 'seee')
    if (error && error.response && error.response.status === 401) {
      routerRedirect()
    }
    if (error && error.message) {
      if (error.message === 'timeout of 10000ms exceeded') {
        return Promise.reject(error)
      }
      if (
        error.response &&
        error.response.status === 500 &&
        error.response.data.msg === '服务器内部错误' 
      ) {
        return Promise.reject(error)
      }
      return new Promise(() => {})
    }
    console.log(error, 'sssssssssssssssssssssssssssssssss')
    return Promise.reject(error)
  }
)

export { httpRequest, axiosPromiseArr }

你可能感兴趣的:(小程序中的axios封装请求)