uView UI组件库http介绍和封装

uni-app项目中,uView是一个非常流行的UI组件库,它内部封装了一个uView-http模块用于网络请求。我们可以在uViewhttp库基础上封装一个通用的请求方法,使其更易于管理和使用。


1. uView http 模块简介

uViewhttp 模块提供了一系列方法来进行网络请求,主要方法如下:

  • setConfig(config):全局配置http请求的默认参数,例如baseURLheader等。
  • request(options):通用的请求方法,支持GETPOST等各种请求方式。
  • get(url, params, config):发起GET请求,params作为查询参数。
  • post(url, params, config):发起POST请求,params作为请求体。
  • put(url, params, config):发起PUT请求。
  • delete(url, params, config):发起DELETE请求。
  • upload(url, options):用于上传文件。
  • custom(options):创建自定义实例,以支持不同的baseURL

2. 封装通用http请求方法

我们可以基于uViewhttp模块封装一个通用的请求方法,具备:

  • 全局配置baseURL、默认header
  • 请求拦截(如:token 处理)
  • 响应拦截(如:错误处理、消息提示)
  • 统一返回数据格式(便于调用时处理)

封装代码

复制代码
// utils/request.js
import Vue from 'vue';
import store from '@/store'; // 假设有 Vuex 进行 token 管理

// uView 的 http 请求库
const http = Vue.prototype.$u.http;

// 配置 http 全局默认参数
http.setConfig((config) => {
    config.baseURL = 'https://api.example.com'; // 你的 API 地址
    config.header = {
        'Content-Type': 'application/json',
    };
    return config;
});

// 请求拦截器
http.interceptor.request = (config) => {
    // 如果 Vuex 存在 token,就在 header 中携带
    const token = store.state.token;
    if (token) {
        config.header['Authorization'] = `Bearer ${token}`;
    }
    return config;
};

// 响应拦截器
http.interceptor.response = (res) => {
    if (res.code === 200) {
        return res.data; // 正常返回数据
    } else {
        // 处理错误
        uni.showToast({
            title: res.msg || '请求错误',
            icon: 'none',
        });
        return Promise.reject(res);
    }
};

// 封装通用请求方法
const request = (url, method = 'GET', data = {}, config = {}) => {
    return new Promise((resolve, reject) => {
        http
            .request({
                url,
                method,
                data,
                ...config,
            })
            .then((res) => {
                resolve(res);
            })
            .catch((err) => {
                reject(err);
            });
    });
};

// 封装 get 请求
const get = (url, params = {}, config = {}) => request(url, 'GET', params, config);

// 封装 post 请求
const post = (url, data = {}, config = {}) => request(url, 'POST', data, config);

// 封装 put 请求
const put = (url, data = {}, config = {}) => request(url, 'PUT', data, config);

// 封装 delete 请求
const del = (url, params = {}, config = {}) => request(url, 'DELETE', params, config);

// 文件上传
const upload = (url, filePath, name = 'file', formData = {}) => {
    return http.upload(url, {
        filePath,
        name,
        formData,
    });
};

export { get, post, put, del, upload };

3. 在 Vue 组件中使用

封装好通用方法后,在组件中可以直接调用,例如:

复制代码
<script>
import { get, post } from '@/utils/request.js';

export default {
    async mounted() {
        try {
            // 发送 GET 请求
            const userData = await get('/user/info');
            console.log('用户信息:', userData);

            // 发送 POST 请求
            const loginRes = await post('/user/login', { username: 'admin', password: '123456' });
            console.log('登录成功:', loginRes);
        } catch (error) {
            console.error('请求出错:', error);
        }
    }
};
</script>

4. uView http 模块各方法的使用

方法 说明 示例
setConfig(config) 设置全局http默认配置 http.setConfig({ baseURL: 'https://api.example.com' });
request(options) 发送通用请求 http.request({ url: '/user', method: 'GET' });
get(url, params, config) 发送GET请求 http.get('/user', { id: 1 });
post(url, params, config) 发送POST请求 http.post('/user', { name: 'Tom' });
put(url, params, config) 发送PUT请求 http.put('/user/1', { name: 'Jack' });
delete(url, params, config) 发送DELETE请求 http.delete('/user/1');
upload(url, options) 文件上传 http.upload('/upload', { filePath, name: 'file' });

5. 总结

通过封装:

  • 减少代码冗余,简化 API 调用方式
  • 统一错误处理 ,避免每个请求都需要 catch
  • 集成 token 处理,提高安全性
  • 支持文件上传,满足多种请求需求

这样封装后,开发时只需 get('/user')post('/login', { username, password }) 就能高效发送请求,代码清晰、易维护。

相关推荐
一颗小青松12 小时前
uniapp输入框fixed定位,导致页面顶起解决方案
前端·uni-app
ttwuai18 小时前
XYGo Admin 菜单与路由:Vue3 动态路由 + GoFrame 权限菜单的完整实现方案
前端·vue·后台框架
2501_9151063218 小时前
深入解析无源码iOS加固原理与方案,保护应用安全
android·安全·ios·小程序·uni-app·cocoa·iphone
万能小林子19 小时前
2026 AI开发新范式:Vibe Coding生成网页 + 3分钟打包成App,非技术人也能独立发布自己的App!
人工智能·uni-app·ai编程·web app·vibecoding
ttwuai21 小时前
XYGo Admin 国际化实战:Vue3 中后台多语言方案详解
前端·javascript·vue.js·vue
一颗小青松21 小时前
uniapp 集成友盟并且上传页面路径
前端·vue.js·uni-app
00后程序员张2 天前
HTTPS单向认证、双向认证、抓包原理与反抓包策略详解
网络协议·http·ios·小程序·https·uni-app·iphone
h_65432102 天前
uniapp-APP端获取拍照时的方向角,同一位置横竖屏拍方向角一致
uni-app
梦梦代码精2 天前
LikeShop按摩到家系统:2026年本地生活创业新风口,上门服务O2O源码私有化部署实战
大数据·docker·小程序·uni-app·生活·高并发·开源软件