vue3的axios封装

Vue3 的 axios封装

import axios, { AxiosPromise, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import qs from 'qs'
import { Toast } from 'vant'
import { encrypt, decrypt } from './index'
import { IParamsType } from '@/types/interface'

type IAxiosResponse<T> = {
  errorCode: string;
  errorMsg: string;
  returnCode: string;
  returnMessage: string;
  data: T;
}

export class Http {
  service: AxiosInstance;
  constructor() {
    console.log(`constructor构造函数中的this:${this}`)
    const errorCreate = (msg: string) => {
      const err = new Error(msg)
      if (process.env.NODE_ENV === 'development') {
        console.log(err)
      }
      Toast.fail(err.message)
      throw err
    }

    this.service = axios.create({
      baseURL: process.env.VUE_APP_BASE_API,
      timeout: 12000
    })

    this.service.interceptors.request.use((config: AxiosRequestConfig) => {
      config.data.body = encrypt(JSON.stringify(config.data.body))
      config.data = JSON.stringify(config.data)
      return config
    }, error => {
      console.log(error)
      return Promise.reject(error)
    })
    // 响应拦截器
    this.service.interceptors.response.use(
      (response: AxiosResponse<any>): any => {
        // AES解密
        try {
          response.data.body = JSON.parse(decodeURIComponent(decrypt(response.data.body)))
        } catch (error) {
          response.data.body = JSON.parse(decrypt(response.data.body))
        }
        const data = response.data.body
        const t = { ...data }
        // delete t.errorCode
        // delete t.errorMsg
        // delete t.returnCode
        // delete t.returnMessage
        const responseData = {
          errorCode: data.errorCode,
          errorMsg: data.errorMsg,
          returnCode: data.returnCode,
          returnMessage: data.returnMessage,
          data: t
        }
        // 这个状态码是和后端约定的
        const { returnCode } = data
        if (!returnCode || returnCode === undefined) {
          errorCreate(`${data.errorMsg}: ${response.config.url}`)
          return false
        }
        console.log('--------data:', data)
        console.log('☞☞☞☞☞☞☞☞responseData:', responseData)
        return responseData
      },
      error => {
        if (error && error.response) {
          switch (error.response.status) {
            case 400:
              error.message = '请求错误'
              break
            case 401:
              error.message = '未授权,请登录'
              break
            case 403:
              error.message = '拒绝访问'
              break
            case 404:
              error.message = `请求地址出错: ${error.response.config.url}`
              break
            case 408:
              error.message = '请求超时'
              break
            case 500:
              error.message = '服务器内部错误'
              break
            case 501:
              error.message = '服务未实现'
              break
            case 502:
              error.message = '网关错误'
              break
            case 503:
              error.message = '服务不可用'
              break
            case 504:
              error.message = '网关超时'
              break
            case 505:
              error.message = 'HTTP版本不受支持'
              break
            default:
              break
          }
        }
        return Promise.reject(error)
      }
    )
  }

  Post<T>(url: string, params: IParamsType, config: AxiosRequestConfig = {}): Promise<IAxiosResponse<T>> {
    const _config = {
      method: 'post',
      url,
      // data: params,
      data: { header: { transCode: params.transCode }, body: { ...params } },
      headers: {
        'Content-Type': 'text/plain;charset=UTF-8'
      }
    }
    config = Object.assign(_config, config)
    return this.service(config)
  }

  Get<T>(url: string, params?: IParamsType, config = {}): Promise<IAxiosResponse<T>> {
    const _config = {
      method: 'get',
      url: url,
      params: params,
      headers: {
        'Content-Type': 'text/plain;charset=UTF-8'
      },
      paramsSerializer: function (params: IParamsType) {
        return qs.stringify(params, { arrayFormat: 'repeat' }) // 修改数组传递格式
      }
    }
    config = Object.assign(_config, config)
    return this.service(config)
  }

  /*
   * JSON格式的接口,默认为post请求
   * 传入 config={method: 'get'}则变为get请求
   */
  Json(url: string, params: IParamsType, config = {}): AxiosPromise {
    const _config = {
      method: 'post',
      url: url,
      data: params,
      headers: {
        'Content-Type': 'application/json'
      }
    }
    config = Object.assign(_config, config)
    return this.service(config)
  }
}

export default new Http()

import CryptoJS from 'crypto-js'
const KEY = CryptoJS.enc.Utf8.parse('202106011234567') // '202106011234567' 与后台一致
/**
 * AES加密
 * @params s    需要加密的字符串
 * @return String  返回加密后的字符串
 */
export const encrypt = (s: string, keyStr?: string): string => {
  const key = (keyStr && CryptoJS.enc.Utf8.parse(keyStr)) || KEY
  const encrypt = CryptoJS.enc.Utf8.parse(s)
  const encrypted = CryptoJS.AES.encrypt(encrypt, key, {
    mode: CryptoJS.mode.ECB, // CryptoJS.mode.CBC
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

/**
 * AES解密
 * @params s    需要加密的字符串
 * @return String  返回加密后的字符串
 */
export const decrypt = (s: string, keyStr?: string): string => {
  const key = (keyStr && CryptoJS.enc.Utf8.parse(keyStr)) || KEY
  const decrypted = CryptoJS.AES.decrypt(s, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Utf8.stringify(decrypted).toString()
}



export function setLocal(key: string, val: any) {
  window.localStorage.setItem(key, encrypt(JSON.stringify(val)))
}

export function getLocal(key: string) {
  return JSON.parse(decrypt(window.localStorage.getItem(key) as string))
}

原文地址:https://www.cnblogs.com/shine-lovely/p/14833305.html