uni-app uni.request网络请求封装

最下面有个缝缝补补最终版

第一种封装方式:使用Promise

request.js

import Vue from 'vue'
Vue.prototype.baseURL = process.env.NODE_ENV === 'development' ? 'http://192.168.0.18:9004' : 'http://***/api' ; //环境配置

export default function http(options) {
	let header = options.header || {};
	let data = options.data || {};

	let token = uni.getStorageSync('token');
	header['token'] = token ? token : "";
 
    //全局参数
	let memberId = uni.getStorageSync('memberId');
	data.memberId = memberId ? memberId : "";
	
	let eaId = uni.getStorageSync('eaId');
	data.eaId = eaId ? eaId : "";

	if (options.url != '/auth/login' && !token) {
		uni.reLaunch({
			url: '/pages/login/login.vue'
		});
		return
	}

	//	发起请求 加载动画
	if (!options.hideLoading) {
		uni.showLoading({
			title: "加载中"
		})
	}
	
	//	发起网络请求
	return new Promise((resolve,reject)=>{
		uni.request({
			url: this.baseURL + options.url,
			method: options.method,
			header: header,
			data: data,
			// dataType: "json",
			// sslVerify: false, //	是否验证ssl证书
			success: res => {
				if (res.statusCode && res.statusCode != 200) {
					return uni.showModal({
						content: res.errMsg ? res.errMsg : '出错了'
					})
				}
				resolve(res.data)
			},
			fail: err => {
				uni.showModal({
					content: err.errMsg? err.errMsg: "出错了"
				})
				reject(err)
			},
            complete: (e) => {
				console.log("请求完成");
				uni.hideLoading()
			}
		})
	})
	
}

main.js中

import Vue from 'vue'
import App from './App'

import request from './common/js/request.js'
Vue.config.productionTip = false

Vue.prototype.$request = request
App.mpType = 'app'

const app = new Vue({
	...App
})
app.$mount()

页面中使用


methods:{
    //或者
    getMessage(){
        this.$request({url: "/markting/h5/isEaH5"}).then((res)=>{
		    console.log(res)
	    })
    },

    //或者
    async getMessage(){
        let res = await this.$request({url: "/hh/apply"})
    }


 }



第二种封装方式:不使用Promise

http.js

import Vue from 'vue'
Vue.prototype.baseURL = process.env.NODE_ENV === 'development' ? 'http://192.168.0.18:9004' : 'http://***/api' ; //环境配置

export default function http(options) {
	let header = options.header || {};
	let data = options.data || {};

	let token = uni.getStorageSync('token');
	header['token'] = token ? token : "";
 
    //全局参数
	let memberId = uni.getStorageSync('memberId');
	data.memberId = memberId ? memberId : "";
	
	let eaId = uni.getStorageSync('eaId');
	data.eaId = eaId ? eaId : "";

	if (options.url != '/auth/login' && !token) {
		uni.reLaunch({
			url: '/pages/login/login.vue'
		});
		return
	}

	//	发起请求 加载动画
	if (!options.hideLoading) {
		uni.showLoading({
			title: "加载中"
		})
	}
	
	//	发起网络请求
	uni.request({
		url: this.baseURL + options.url,
		method: options.method,
		header: header,
		data: data,
		// dataType: "json",
		// sslVerify: false, //	是否验证ssl证书
		success: res => {
			if (res.statusCode && res.statusCode != 200) {
				return uni.showModal({
					content: res.errMsg ? res.errMsg : '出错了' // 
				})
			}
			typeof options.success == "function" && options.success(res.data);
		},
		fail: err => {
			uni.showModal({
				content: err.errMsg? err.errMsg: "出错了"
			})
			typeof options.fail == "function" && options.fail(err.data);
		},
		complete: (e) => {
			console.log("请求完成");
			uni.hideLoading()
			typeof options.complete == "function" && options.complete(e);
			return;
		}
	})
}

main.js

import Vue from 'vue'
import App from './App'
import http from './common/js/http.js'

Vue.config.productionTip = false

Vue.prototype.$http = http

App.mpType = 'app'

const app = new Vue({
	...App
})
app.$mount()

页面中使用

getMessage(){
    this.$http({
	    url: "/hh/apply",
	    method: 'POST',
	    data: this.form,
	    success: (res) => {
		    console.log(res)
		    uni.showToast({
			    title: '申请成功',
			    duration: 1000
		    });
	    }
    })
}

缝缝补补最终版

import Vue from 'vue'
 Vue.prototype.baseURL = process.env.NODE_ENV === 'development' ? 'http://192.168.0.20:8080' : 'http://xxx'; //环境配置

export default function request(options) {
	let header = options.header || {};
	let data = options.data || {};

	let token = uni.getStorageSync('token');
	header['token'] = token ? token : "";
	
    //需要token的接口但是没有token
	if (!options.notNeedToken && !token) {
		uni.reLaunch({
			url: '/pages/loginByAccount/loginByAccount'
		});
		return new Promise((resolve, reject) => {
			reject({code:12,msg:'请登录'})
		})
	}

	//	发起请求 加载动画
	if (!options.hideLoading) {
		uni.showLoading({
			title: "加载中"
		})
	}

	//	发起网络请求
	return new Promise((resolve, reject) => {
		uni.request({
			url: this.baseURL + options.url,
			method: options.method || 'GET',
			header: header,
			data: data,
			// dataType: "json",
			// sslVerify: false, //	是否验证ssl证书
			success: res => {
				if (res.statusCode && res.statusCode != 200) {
					return uni.showModal({
						content: res.errMsg ? res.errMsg : '出错了'
					})
				}
                //登录失效 token失效
				if(res.data.code === 100005002){
					uni.showToast({
						icon:'none',
						duration:3000,
						title:'登录失效,请重新登录'
					})
					return uni.reLaunch({
						url:'/pages/loginByAccount/loginByAccount.vue'
					})
				}
				resolve(res.data)
			},
			fail: err => {
				uni.showModal({
					content: err.errMsg ? err.errMsg : "出错了"
				})
				reject(err)
			},
			complete: (e) => {
				uni.hideLoading()
				uni.stopPullDownRefresh();
			}
		})
	})

}

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值