Vue Native应用中的API请求封装:拦截器与统一处理

【免费下载链接】vue-native-core Vue Native is a framework to build cross platform native mobile apps using JavaScript 【免费下载链接】vue-native-core 项目地址: https://gitcode.com/gh_mirrors/vu/vue-native-core

你是否还在为Vue Native应用中的API请求处理烦恼?重复的错误处理代码、混乱的请求头管理、难以追踪的网络异常...本文将带你一步实现API请求的优雅封装,通过拦截器与统一处理方案,让网络请求代码从此变得简洁可维护。

为什么需要封装API请求

在移动应用开发中,API交互是核心环节。一个未封装的项目往往充斥着以下问题:

  • 重复的fetchaxios调用代码
  • 分散在各组件中的错误处理逻辑
  • 难以统一管理的请求头和认证信息
  • 缺乏请求/响应的全局拦截能力

通过封装,我们可以将这些问题一网打尽。Vue Native虽然没有内置API请求模块,但我们可以利用JavaScript的语言特性和Vue的插件系统构建强大的请求层。项目中提供的工具函数src/core/util/index.js包含了许多实用方法,将帮助我们实现这一目标。

核心实现方案

请求拦截器设计

请求拦截器的主要作用是在请求发送前统一处理配置,如添加认证令牌、设置请求头等。以下是基于Vue原型的拦截器实现:

// src/utils/api.js (项目中建议创建此文件)
import Vue from 'vue'
import { mergeOptions } from '../core/util/index'

// 创建拦截器容器
const interceptor = {
  request: [],
  response: []
}

// 注册请求拦截器
Vue.prototype.$http = {
  interceptors: {
    request: {
      use(fn) {
        interceptor.request.push(fn)
      }
    },
    response: {
      use(fn) {
        interceptor.response.push(fn)
      }
    }
  },
  
  // 核心请求方法
  async request(options) {
    // 应用请求拦截器
    let config = mergeOptions({
      headers: {
        'Content-Type': 'application/json'
      },
      timeout: 10000
    }, options)
    
    interceptor.request.forEach(fn => {
      config = fn(config) || config
    })
    
    try {
      const response = await fetch(config.url, config)
      // 应用响应拦截器
      interceptor.response.forEach(fn => {
        response.data = fn(response.data) || response.data
      })
      return response
    } catch (error) {
      // 统一错误处理
      console.error('API Error:', error)
      throw error
    }
  }
}

统一错误处理机制

结合项目中的错误处理工具src/core/util/error.js,我们可以构建更完善的异常处理体系:

// 响应拦截器实现错误统一处理
Vue.prototype.$http.interceptors.response.use(response => {
  if (response.status >= 400) {
    // 使用项目内置错误处理工具
    const error = new Error(`Request failed with status ${response.status}`)
    error.response = response
    // 可调用[src/core/util/error.js](https://link.gitcode.com/i/7d9bdb7aeb1f3956cf80e904f767e14e)中的错误处理方法
    handleError(error)
    throw error
  }
  return response
})

// 常见错误处理函数
function handleError(error) {
  switch(error.response.status) {
    case 401:
      // 未授权,跳转登录页
      Vue.prototype.$navigateTo({ name: 'Login' })
      break
    case 403:
      // 权限不足提示
      alert('您没有操作权限')
      break
    case 404:
      // 资源不存在提示
      alert('请求的资源不存在')
      break
    default:
      // 其他错误
      alert('网络异常,请稍后重试')
  }
}

实战应用示例

基础请求封装

// src/api/user.js (建议按业务模块拆分)
export default {
  // 用户登录
  login(credentials) {
    return Vue.prototype.$http.request({
      url: 'https://api.example.com/login',
      method: 'POST',
      body: JSON.stringify(credentials)
    })
  },
  
  // 获取用户信息
  getUserInfo() {
    return Vue.prototype.$http.request({
      url: 'https://api.example.com/user/info',
      method: 'GET'
    })
  }
}

在组件中使用

// 组件中调用示例
export default {
  methods: {
    async doLogin() {
      try {
        const response = await this.$api.user.login({
          username: this.username,
          password: this.password
        })
        // 存储令牌 (可使用Vuex或本地存储)
        this.$store.commit('setToken', response.data.token)
        this.$navigateTo({ name: 'Home' })
      } catch (error) {
        // 错误已在拦截器中统一处理
      }
    }
  }
}

高级优化建议

  1. 请求队列管理:实现并发请求控制,避免请求风暴
  2. 缓存策略:结合src/core/util/index.js中的工具方法实现请求结果缓存
  3. 取消请求:添加请求取消机制,解决页面切换时的请求泄漏问题
  4. 请求状态管理:配合Vuex实现全局加载状态管理

总结与资源

通过本文介绍的拦截器与统一处理方案,你已经掌握了Vue Native应用中API请求的优雅处理方式。这种架构不仅提高了代码复用率,还大大增强了项目的可维护性。

希望本文能帮助你构建更健壮的Vue Native应用。如果觉得有帮助,请点赞收藏,关注后续更多Vue Native开发技巧!

【免费下载链接】vue-native-core Vue Native is a framework to build cross platform native mobile apps using JavaScript 【免费下载链接】vue-native-core 项目地址: https://gitcode.com/gh_mirrors/vu/vue-native-core

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐