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 }) 就能高效发送请求,代码清晰、易维护。

相关推荐
前端小雪的博客.8 小时前
Uniapp 小程序复制、粘贴功能实现
小程序·uni-app
竣子好逑9 小时前
uniapp v2 组件
前端·uni-app
筱歌儿9 小时前
uniapp 阿里云点播 播放bug
uni-app·bug
陆康永9 小时前
uniapp-X 对象动态取值
uni-app
林涧泣9 小时前
【Uniapp-Vue3】登录成功后获取当前用户信息并渲染到页面中
前端·javascript·uni-app
前端小雪的博客.9 小时前
Uniapp 小程序接口封装与使用
微信小程序·uni-app
离别又见离别9 小时前
uniapp 本地数据库多端适配实例(根据运行环境自动选择适配器)
数据库·vue.js·sqlite·uni-app·db
香菜的开发日记9 小时前
uniapp 系统学习,从入门到实战(四)—— 页面与路由管理
uni-app
lyz2468599 小时前
uniapp h5页面获取跳转传参的简单方法
uni-app
前端小雪的博客.9 小时前
Uniapp 小程序:语音播放与暂停功能的实现及优化方案
前端·小程序·uni-app