uniapp封装网络请求

新建utils工具目录,新建http.js文件

const configObj = {
//设置服务器根目录
    baseUrl: '',
}
const exceptionMessage = {
    '200':'请求成功',
    '301':'资源被永久转移到其它URL',
    '404': '请求的资源不存在',
    '500': '内部服务器错误'    
}
class Http {
    static async request(options) {
        Http._beforeRequest()
        options.url = configObj.baseUrl + options.url
        console.log("请求参数是",options)
        const response = await uni.request(options)
        console.log("请求结果是",response)
        // 对响应信息做处理
        return Http._afterResponse(response)
    }
    // 请求拦截器
    static _beforeRequest() {
        uni.showLoading({
            title:'数据加载中……'
        })    
    }
    
    // 响应拦截器
    static  _afterResponse(response){
        uni.hideLoading()
        // 这个要看接口数据是什么结构
        const {message,meta}= response[1].data
        if(meta.status !==200){
            Http._showError(meta.status,meta.msg)
        }
        console.log("经过处理的请求结果是",message)
        return message
    }
    // 请求错误信息提示
    static _showError(code,msg){
        let title = ''
        title = exceptionMessage[code] || msg || '发生未知错误'
        uni.showToast({
            duration:1500,
            title:title,
            icon:"none"
        })
    }
}
export default Http

项目根目录下,新建api目录,新建request.js文件, 继承Http类

import Http from '../utils/http.js'

class Request extends Http{
    static getSwiperList(){
        return Http.request({
            url:'/api/public/v1/home/swiperdata',
            method:'GET'
        })
    }
}
export default Request

在main.js中引入请求类,并设置成全局对象uni的属性。

import Request from './api/request.js'
uni.$http = Request

在组件中使用

        onLoad() {
            this.getData()
        },
        methods: {
            async getData() {
                let result = await uni.$http.getSwiperList()
                if (result != null) {
                    this.swiperList = result
                }
            }
        }

来看效果,真的绝了。O(∩_∩)O哈哈~

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值