uniapp封装请求

在uniapp中封装HTTP请求,通常我们会使用uni.request方法。uni.request是uni-app提供的一个网络请求API,可以用来发送各种类型的HTTP请求(GET、POST、PUT、DELETE等)。下面是如何在uniapp中封装一个通用的HTTP请求方法,以便于在项目的各个部分复用。

1. 创建请求方法

首先,你可以在项目的utils目录下创建一个http.js文件,用于封装HTTP请求。

// utils/http.js
 
import store from '@/store' // 如果使用Vuex,引入store
 
const baseUrl = 'https://你的接口域名'; // 你的接口基础URL
 
function request(options) {
    const { url, method = 'GET', data = {}, headers = {} } = options;
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            method,
            data,
            header: {
                ...headers,
                'content-type': 'application/json' // 根据需要设置内容类型
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    resolve(res.data); // 成功时返回数据
                } else {
                    reject(res); // 失败时返回错误信息
                }
            },
            fail: (error) => {
                reject(error); // 请求失败时返回错误信息
            }
        });
    });
}
 
export default request;

2. 使用拦截器(可选)

为了增强请求的灵活性,比如添加统一的请求头、处理登录状态、错误提示等,你可以添加请求拦截器和响应拦截器。例如:

// utils/http.js (修改后的版本)
import store from '@/store'; // 引入store,如果使用Vuex的话
 
const baseUrl = 'https://你的接口域名'; // 你的接口基础URL
const tokenKey = 'your_token_key'; // 假设token存储在这个key中,根据实际情况修改
 
function request(options) {
    const { url, method = 'GET', data = {}, headers = {} } = options;
    const token = uni.getStorageSync(tokenKey); // 获取token,根据实际情况调整获取方式
    const defaultHeaders = {
        'Authorization': token ? `Bearer ${token}` : '', // 如果存在token,则添加到请求头中
        'content-type': 'application/json' // 根据需要设置内容类型
    };
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            method,
            data,
            header: { ...defaultHeaders, ...headers }, // 使用展开运算符合并默认头和自定义头
            success: (res) => {
                if (res.statusCode === 200) {
                    resolve(res.data); // 成功时返回数据
                } else if (res.statusCode === 401) { // 例如,处理401未授权错误,可能需要重新登录等操作
                    // 可以根据实际情况处理,例如跳转到登录页面等
                    reject(new Error('Unauthorized')); // 或者其他错误处理逻辑
                } else {
                    reject(res); // 其他错误情况返回错误信息
                }
            },
            fail: (error) => {
                reject(error); // 请求失败时返回错误信息
            }
        });
    });
}

3. 在项目中调用封装的方法

现在你可以在项目的其他部分通过引入http.js来使用封装的request方法了。例如:

import request from '@/utils/http'; // 引入封装的方法
 
export default {
    methods: {
        fetchData() {
            request({ url: '/api/data', method: 'GET' })
                .then(data => {
                    console.log(data); // 处理返回的数据
                })
                .catch(error => {
                    console.error(error); // 处理错误情况
                });
        }
    }
}

这样,你就可以在uniapp中方便地使用封装好的HTTP请求方法了。

相关推荐
一个处女座的程序猿O(∩_∩)O2 小时前
Uniapp 开发中遇到的坑与注意事项:全面指南
uni-app
Elena_Lucky_baby2 小时前
uniapp 网络请求封装(uni.request 与 uView-Plus)
uni-app
黑云压城After6 小时前
uniapp小程序自定义日历(签到、补签功能)
小程序·uni-app
烂蜻蜓6 小时前
Uniapp 设计思路全分享
前端·css·vue.js·uni-app·html
尚学教辅学习资料7 小时前
基于SpringBoot+Vue+uniapp的高校招聘小程序+LW参考示例
spring boot·uni-app·招聘系统
岑梓铭9 小时前
uniapp邪门事件
uni-app
漫天绯羽10 小时前
uniapp 中使用天地图,安卓端、h5
uni-app
尚学教辅学习资料12 小时前
基于SpringBoot+vue+uniapp的智慧旅游小程序+LW示例参考
vue.js·spring boot·uni-app·旅游
烂蜻蜓17 小时前
前端已死?什么是前端
开发语言·前端·javascript·vue.js·uni-app