技术 · 思考 · 实践 · 成长

首页/UniAPP专题/正文

uniapp 网络请求与 API 封装:uni.request、Promise 化与拦截器

UniAPP专题3 次阅读

页面数据都靠接口。把 uni.request 封装成带拦截器的请求库是工程化第一步,附完整封装小案例。

一、uni.request 基础

uni.request({
  url: 'https://api.example.com/user/1',
  method: 'GET',
  data: { id: 1 },
  header: { 'Authorization': 'Bearer ' + token },
  success: (res) => console.log(res.data),
  fail: (err) => console.error(err)
})

二、Promise 封装

// utils/request.js
const BASE_URL = 'https://api.example.com'

const request = (options) => new Promise((resolve, reject) => {
  uni.request({
    url: BASE_URL + options.url,
    method: options.method || 'GET',
    data: options.data || {},
    header: { 'Authorization': 'Bearer ' + uni.getStorageSync('token') },
    success: (res) => resolve(res.data),
    fail: reject
  })
})

export default request

三、拦截器(重点)

// 统一处理:token、错误码、loading
const request = async (options) => {
  if (options.loading !== false) uni.showLoading({ title: '加载中' })  // 请求拦截
  try {
    const res = await rawRequest(options)
    // 响应拦截:业务错误码统一处理
    if (res.code === 0) return res.data
    if (res.code === 401) {                    // token 失效
      uni.removeStorageSync('token')
      uni.navigateTo({ url: '/pages/user/login' })
      return Promise.reject(res)
    }
    uni.showToast({ title: res.message, icon: 'none' })
    return Promise.reject(res)
  } catch (e) {
    uni.showToast({ title: '网络异常', icon: 'none' })
    return Promise.reject(e)
  } finally {
    uni.hideLoading()                          // 收尾
  }
}

四、业务 API 模块化

// api/user.js
import request from '@/utils/request'
export const getUser  = (id) => request({ url: `/user/${id}` })
export const login    = (data) => request({ url: '/login', method: 'POST', data })

// 页面调用
const { getUser } = require('@/api/user')
const user = await getUser(1)

五、注意

  • 小程序必须在 mp 后台配置合法域名(开发期可勾"不校验");
  • 并发请求多时 loading 用计数(防提前隐藏);
  • GET 参数放 data、POST 也放 data(uni 自动转 body);
  • 上传文件用 uni.uploadFile(别用 request)。

六、小案例:完整 api 封装库

// utils/request.js 完整版
const BASE_URL = process.env.VUE_APP_BASE_API || 'https://api.example.com'
let loadingCount = 0

const showLoading = () => {
  if (loadingCount++ === 0) uni.showLoading({ title: '加载中', mask: true })
}
const hideLoading = () => {
  if (--loadingCount <= 0) { loadingCount = 0; uni.hideLoading() }
}

const request = (options) => new Promise((resolve, reject) => {
  options.loading !== false && showLoading()
  uni.request({
    url: BASE_URL + options.url,
    method: options.method || 'GET',
    data: options.data,
    timeout: 10000,
    header: { 'Authorization': 'Bearer ' + uni.getStorageSync('token') },
    success: (res) => {
      if (res.data.code === 0) return resolve(res.data.data)
      if (res.data.code === 401) {
        uni.removeStorageSync('token')
        uni.navigateTo({ url: '/pages/user/login' })
      } else {
        uni.showToast({ title: res.data.message, icon: 'none' })
      }
      reject(res.data)
    },
    fail: (err) => {
      uni.showToast({ title: '网络异常', icon: 'none' })
      reject(err)
    },
    complete: () => options.loading !== false && hideLoading()
  })
})

;['get', 'post', 'put', 'delete'].forEach(m => {
  request[m] = (url, data, opts = {}) => request({ url, data, method: m.toUpperCase(), ...opts })
})

export default request

Promise + loading 计数 + 401 跳登录 + restful 方法挂载 —— 可直接搬进项目的请求库。

七、总结

uni.request 封装 Promise;拦截器管 token/错误码/loading;API 按模块拆文件;合法域名必配;loading 用计数防抖。

好的习惯,排名第一的是:自律;排名第二的是:终身学习;排名第三的是:保持运动。拥有这三种习惯,美好人生垂手可得。

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读