当前位置:首页 > uni-app

uniapp请求库封装

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

uniapp 请求库封装方法

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

基础封装示例

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

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 }

使用示例

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

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

uniapp怎么启动

uniapp怎么启动

启动UniApp项目的步骤 确保已安装Node.js(建议版本12+)和HBuilderX(官方IDE)。若未安装,需先下载并配置环境。 安装开发工具 从HBuilderX官网下载对应操作系统的版本…

uniapp部署到服务器

uniapp部署到服务器

部署准备 确保本地开发环境已完成项目构建,生成静态文件(H5端为/dist/build/h5目录)。检查服务器环境是否安装Nginx/Apache等Web服务软件,并配置好域名解析。 上传文件 通过…

uniapp安装axios

uniapp安装axios

安装axios 在uniapp项目中安装axios需要确保项目支持node_modules管理。通过npm或yarn安装axios: npm install axios # 或 yarn add a…

uniapp判断手机定位是否开启

uniapp判断手机定位是否开启

判断手机定位是否开启的方法 在UniApp中判断手机定位是否开启,可以通过调用原生API或使用第三方插件实现。以下是几种常见的方法: 使用uni.getLocation检测定位状态 通过调用uni.…

uniapp指南

uniapp指南

开发环境搭建 下载HBuilderX作为官方推荐的开发工具,支持Windows和Mac系统。安装后创建uni-app项目,选择模板(如默认模板、Hello Uni-app等)。确保Node.js版本在…