有学有练才叫学习:学而不思则罔,思而不学则殆:学而不习,纸上谈兵,习而不进,画地为牢!

vue3 + ts Axios 接口封装(实现方式)详细步骤

vue 炮渣日记 4周前 (11-10) 71次浏览 已收录 0个评论 扫描二维码

1、首先在项目src下面创建一个全局配置文件 config.ts 文件

//项目名称
export const PROJECT_NAME = 'xxxxx'
// 静态资源的地址
export const STATIC_IMAGE_URL = 'xxx' 
// 接口地址
export const HTTP_REQUEST_URL = 'xxx'

//请求头信息

export const HEADER = {
  'content-type': 'application/json',
}

export const HEADERPARAMS = {
  'content-type': 'application/x-www-form-urlencoded',
}

export const TOKENNAME = 'Authorization'

2、接下来在utils创建一个 requestClass.ts 文件

//新增的Symbol类型,可以解决命名重名的问题,多用于设置对象属性
const config = Symbol('config')
const isCompleteURL = Symbol('isCompleteURL')
const requestBefore = Symbol('requestBefore')
const requestAfter = Symbol('requestAfter')

class requestClass {
  // 默认配置
  [config]: { baseURL?: string } & UniApp.RequestOptions = {
    baseURL: '',
    url: '',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    method: 'GET',
    timeout: 3000,
    dataType: 'json',
    responseType: 'text'
  }

  // 拦截器
  interceptors = {
    request: (func: Fn) => {
      if (func) {
        requestClass[requestBefore] = func
      } else {
        requestClass[requestBefore] = (request) => request
      }
    },
    response: (func: Fn) => {
      if (func) {
        requestClass[requestAfter] = func
      } else {
        requestClass[requestAfter] = (response) => response
      }
    },
  }

  // 请求之前,是默认配置
  static [requestBefore](config: UniApp.RequestOptions) {
    return config
  }
  // 请求之后,默认配置发生改变的话
  static [requestAfter](response: any) {
    return response
  }
  // 判断url是否完整
  static [isCompleteURL](url: string) {
    return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
  }

  request(options: UniApp.RequestOptions & { baseURL?: string }) {
    options.baseURL = options.baseURL || this[config].baseURL
    options.dataType = options.dataType || this[config].dataType
    options.url = requestClass[isCompleteURL](options.url) ? options.url : (options.baseURL + options.url)
    options.data = options.data
    options.header = { ...options.header, ...this[config].header }
    options.method = options.method || this[config].method

    options = { ...options, ...requestClass[requestBefore](options) }

    return new Promise((resolve, reject) => {
      options.success = function (res) {
        resolve(requestClass[requestAfter](res))
      }
      options.fail = function (err) {
        reject(requestClass[requestAfter](err))
      }
      uni.request(options)
      // 请求中断
       let obj: any = {}
       obj[request.url] = uni.request(options)
       abortRequest() {
         for (const key in obj) {
           if (Object.prototype.hasOwnProperty.call(obj, key)) {
             const element = obj[key];
             element.abort()
           }
         }
       }
    })
  }

//声明请求类型
  get(url: string, data: any = {}, options: Recordable = {}) {
    return this.request({ ...options, url, data, method: 'GET' })
  }

  post(url: string, data: any = {}, options: Recordable = {}) {
    return this.request({ ...options, url, data, method: 'POST' })
  }

  put(url: string, data: any = {}, options: Recordable = {}) {
    return this.request({ ...options, url, data, method: 'PUT' })
  }

  delete(url: string, data: any = {}, options: Recordable = {}) {
    return this.request({ ...options, url, data, method: 'DELETE' })
  }

  getConfig() {
    return this[config]
  }
  
  // 修改默认配置的一个方法,可以修改请求地址,请求方式等等
  setConfig(func: Fn) {
    this[config] = func(this[config])
  }
}

export default requestClass

3、接下来在utils创建 request.ts 文件

import requestClass from './requestClass'
import { HEADER, HEADERPARAMS, TOKENNAME, HTTP_REQUEST_URL } from '@/config/app'
import qs from 'qs'

const Request = new requestClass()

// 请求拦截器
Request.interceptors.request((request: any) => {
  if (request.header.contentType) {
    request.header['content-type'] = request.header.contentType
    delete request.header.contentType
  }
  if (request.method === 'GET') {
    request.data = qs.stringify(request.data)
    request.url = request.url + '?' + request.data
  }
  return request
})

// 响应拦截器
Request.interceptors.response((response: any) => {
  const token = uni.getStorageSync('userDate').token
  if (response.data.code === 403) {
    //uni-app 提示,本地存储,可自行修改
    uni.showToast({
      title: token ? '请重新登录' : '请先登录',
      icon: 'none',
      duration: 2000,
    })
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
  }
  return response
})

// 设置默认配置
Request.setConfig((config: any) => {
  config.baseURL = HTTP_REQUEST_URL
  //判断是否存在用token,放入请求头
  if (uni.getStorageSync('userDate').token) {
    config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token')
    config.header['token'] = uni.getStorageSync('userDate').token
  }
  return config
})

export default Request

4、调用接口

我们可以在项目src下建立我们的api接口信息 (api => index.ts)

import request from '@/utils/request'

const options = {
  header: { 'content-type': 'application/x-www-form-urlencoded'},
  token: uni.getStorageSync('userDate').token
}
/**
 *  测试接口
 */
export function testGet(data :any) {
  return request.get('/api/kecheng/getchargekechenginfo', data)
}

export function testPost(data :any) {
  return request.post('/api/kecheng/getlistsuddenstudy', data, options)
}

export function testPut(data :any) {
  return request.post('/testPut', data)
}

export function testDelete(data :any) {
  return request.delete('/testDelete', data)
}

//正式接口
//用户授权登录基本信息
export function userLoginFor(data :any) {
  return request.get('/wxoauth/oauthlogin', data)
}

喜欢 (0)
炮渣日记
关于作者:
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址