美文网首页Vuemui
uni-app 服务端请求封装

uni-app 服务端请求封装

作者: 橙小光 | 来源:发表于2019-12-17 16:00 被阅读0次

自己封装的uni-app服务端请求,包括 异常捕获、loading开启关闭、特殊请求基础地址、header的token配置、请求编码为application/json或application/x-www-form-urlencoded

http.js

// created by wangyong for uni-app request 2019.11.22
const baseURL = 'http://localhost:8888/vec';
const http = (options) => {
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: '加载中...',
            mask: options.load || false // 默认遮罩出现可以继续操作
        });
        try{
            uni.request({
                url: (options.baseURL || baseURL) + options.url,
                method: options.method || 'POST', // 默认为POST请求
                data: options.data, //请求超时在manifest.json配置
                header: {
                    'v-token': '333333',
                    'Content-Type': options.header == 'form' ? 'application/x-www-form-urlencoded' : 'application/json'
                },
                success: res => {
                    resolve(res.data)
                },
                fail: (err) => {
                    reject(err.data);
                    console.log(err);
                    uni.showToast({
                        title: '请检查网络连接',
                        icon: 'none'
                    })
                    /*错误码处理
                    let code = err.data.code; 
                    switch (code) {
                        case 1000:
                            break;
                        default:
                            break;
                    } */
                },
                complete: () => {
                    uni.hideLoading();
                }
            });
        }catch(e){
            uni.hideLoading();
            uni.showToast({
                title: '服务端异常',
                icon: 'none'
            })
        }
        
    })
}

export default http

main.js 添加

import http from './common/http.js'

Vue.prototype.$HTTP = http

调用实例:

this.$HTTP({
  method: 'POST',
  url: '/api/news',
  data: {},
 // baseURL:'http://www.buwang.com'
 // header:'form' 
}).then((res) =>{
  console.log(res)
}
// (err)=>{ console.log(err) }
)

相关文章

网友评论

    本文标题:uni-app 服务端请求封装

    本文链接:https://www.haomeiwen.com/subject/uhosnctx.html