当前位置:首页 > uni-app

uniapp请求库封装

2026-03-05 11:18:16uni-app

uniapp 请求库封装方法

uniapp 的请求功能基于 uni.request,但直接使用可能不够灵活。通过封装可以统一处理请求参数、响应数据、错误处理等逻辑,提升开发效率和代码可维护性。

基础封装示例

创建一个 request.js 文件,封装基础的请求功能:

uniapp请求库封装

const BASE_URL = 'https://your-api-domain.com/api'

const request = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

export default request

添加拦截器功能

扩展基础封装,加入请求和响应拦截器:

const interceptors = {
  request: [],
  response: []
}

const addRequestInterceptor = (callback) => {
  interceptors.request.push(callback)
}

const addResponseInterceptor = (callback) => {
  interceptors.response.push(callback)
}

const runInterceptors = async (type, value) => {
  for (const interceptor of interceptors[type]) {
    value = await interceptor(value)
  }
  return value
}

const enhancedRequest = async (options) => {
  try {
    options = await runInterceptors('request', options)
    const response = await request(options)
    return await runInterceptors('response', response)
  } catch (error) {
    throw error
  }
}

export { enhancedRequest as request, addRequestInterceptor, addResponseInterceptor }

使用示例

在页面或组件中导入并使用封装后的请求库:

uniapp请求库封装

import { request, addRequestInterceptor, addResponseInterceptor } from '@/utils/request'

// 添加请求拦截器
addRequestInterceptor((config) => {
  const token = uni.getStorageSync('token')
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`
    }
  }
  return config
})

// 添加响应拦截器
addResponseInterceptor((response) => {
  if (response.code !== 0) {
    uni.showToast({
      title: response.message || '请求失败',
      icon: 'none'
    })
    throw new Error(response.message)
  }
  return response.data
})

// 发起请求
const fetchData = async () => {
  try {
    const result = await request({
      url: '/user/info',
      method: 'GET'
    })
    console.log(result)
  } catch (error) {
    console.error(error)
  }
}

高级功能扩展

针对更复杂的场景,可以进一步扩展封装:

// 超时设置
const requestWithTimeout = (options, timeout = 10000) => {
  return Promise.race([
    request(options),
    new Promise((_, reject) => {
      setTimeout(() => {
        reject(new Error('请求超时'))
      }, timeout)
    })
  ])
}

// 取消请求
const createCancelToken = () => {
  let cancel
  const token = new Promise((resolve) => {
    cancel = resolve
  })
  return { token, cancel }
}

// 并发控制
const createRequestQueue = (maxConcurrent = 5) => {
  const queue = []
  let running = 0

  const runNext = () => {
    if (running >= maxConcurrent || queue.length === 0) return
    running++
    const { task, resolve, reject } = queue.shift()
    task()
      .then(resolve)
      .catch(reject)
      .finally(() => {
        running--
        runNext()
      })
  }

  return (task) => {
    return new Promise((resolve, reject) => {
      queue.push({ task, resolve, reject })
      runNext()
    })
  }
}

类型提示(TypeScript)

如果使用 TypeScript,可以添加类型定义:

interface RequestOptions {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
  data?: any
  header?: Record<string, string>
}

interface ResponseData<T = any> {
  code: number
  message: string
  data: T
}

type Interceptor<T> = (value: T) => T | Promise<T>

const request = <T>(options: RequestOptions): Promise<ResponseData<T>> => {
  // 实现同上
}

通过以上封装,可以构建一个功能完善、易于维护的 uniapp 请求库,满足各种业务场景需求。

标签: uniapp
分享给朋友:

相关文章

uniapp 极光推送

uniapp 极光推送

uniapp 集成极光推送的方法 在 uniapp 中集成极光推送,需要使用官方提供的插件或自行封装原生模块。以下是具体实现方式: 使用官方插件 在 uni-app 插件市场搜索「极光推送」插件,…

uniapp 线程

uniapp 线程

uniapp 线程的概念 在 uniapp 中,线程的概念与原生应用开发有所不同。由于 uniapp 是基于 JavaScript 的运行环境,它并不直接支持多线程操作。JavaScript 本身是单…

uniapp grid

uniapp grid

uniapp grid 布局实现方法 在 uniapp 中实现 grid 布局可以通过多种方式完成,包括使用内置组件、CSS Grid 或第三方插件。以下是几种常见的实现方法: 使用 uni-gri…

uniapp 服务文件

uniapp 服务文件

uniapp 服务文件的概念 在 uniapp 中,服务文件通常指用于封装业务逻辑、接口请求或通用功能的 JavaScript 文件。这类文件通常存放在项目的 common 或 utils 目录下,便…

uniapp滑动图标

uniapp滑动图标

uniapp滑动图标的实现方法 使用swiper组件实现横向滑动图标 在uniapp中可以通过swiper组件实现图标的横向滑动效果。以下是一个基础示例代码: <template>…

uniapp 后台播报

uniapp 后台播报

uniapp 实现后台播报的方法 在uniapp中实现后台播报功能,主要涉及音频播放和后台运行权限的配置。以下是具体实现方法: 使用uni.getBackgroundAudioManager uni…