uni-app 的 request 请求封装方式有很多种,这里介绍一种原生的封装方式。

创建 http.js

在项目根路径下新建 commons 文件夹,并创建一个 http.js,内容如下:

const baseUrl = 'http://127.0.0.1:8080/api/'

const showToast = (title) => {
    uni.showToast({
        title: title,
        icon: 'none'
    })
}

/**请求接口
 * @method http
 * @param {String} url 接口地址
 * @param {Object} obj 接口配置和参数
 * @return {Object} requestTask
 */
const http = (url, obj) => {
    let option = obj.option || {}
    let hideLoading = option.hideLoading || false // 是否显示 loading
    let hideMsg = option.hideMsg || false // 是否隐藏错误提示
    let data = obj.data || {} // 请求数据
    let token = '' // 登录鉴权获得的 token
    uni.getStorage({
        key: 'token',
        success: (ress) => {
            token = ress.data
        }
    })
    if (!hideLoading) {
        uni.showLoading({
            title: '加载中...',
            mask: true
        })
    }
    return uni.request({
        url: baseUrl + url,
        method: option.method || 'POST', // 默认 post 请求
        header: {
            'Token': token
        },
        data: data,
        success: res => { // 服务器成功返回的回调函数
            if (!hideLoading) uni.hideLoading()
            if (res.statusCode === 200) {
                let result = res.data
                if (result.errcode === '0') {
                    if (obj.success) obj.success(result)
                    return
                }
                if (obj.fail) obj.fail(result.errmsg)
                if (!hideMsg) showToast(result.errmsg)
            } else { // 返回值非 200,强制显示提示信息
                showToast('[' + res.statusCode + '] 系统处理失败')
                if (obj.fail) obj.fail('[' + res.statusCode + '] 系统处理失败')
            }
        },
        fail: (err) => { // 接口调用失败的回调函数
            if (!hideLoading) uni.hideLoading()
            if (err.errMsg != 'request:fail abort') {
                showToast('连接超时,请检查您的网络。')
                if (obj.fail) obj.fail('连接超时,请检查您的网络。')
            }
        }
    })
}
export default http

导入和使用 http.js

在需要请求接口的地方导入 http.js。

import http from '@/commons/http.js'

具体使用方式如下:

const requestTask = http('data/get', {
    data: {
        id: id
    },
    option: {
        hideLoading: false, // 默认 false
        hideMsg: true, // 默认 false
        method: 'POST' // 默认 POST
    },
    success: res => {
        console.log(res.data)
    },
    fail: err => {
        console.log(err)
    }
})

// 如果需要的话,可以通过改方法中断请求任务
requestTask.abort()

如有更好的封装方式,欢迎留言交流。

如果觉得我的文章对你有用,请点个赞