自身用promise封装uni.request

原生的uni.requestAPI有promise形式,晚上也有uni-request封装模仿类axios(我在调用的时候出了问题,还没找到原因)

在基于以下情况决定自己封装

1.post请求要设置header['content-type'] 为 application/x-www-form-urlencoded

2.塞token

3.每次调用接口返回都要根据statusCode进行不同处理,封装后做统一的行动

4.有些接口的反应时间有几秒,统一添加加载状态(之后可能有)

在项目目录common的url.js写入

function urlRequest(url, data, method, header = {'content-type': 'application/json'}) {
	if (method === 'post') {
		header['content-type'] = 'application/x-www-form-urlencoded'
	}
	if (uni.getStorageSync('token') != '') {
		header['Authorization'] = uni.getStorageSync('token')
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			data,
			method,
			header,
			success: (res) => {
				console.log('request success', res)
				if (res.statusCode == 200) {
					resolve(res)
				}
				if (res.statusCode == 401) {
					uni.showToast({
						icon: 'none',
						title: '请求方法错误',
						duration: 1500
					});
				}
				if (res.statusCode == 401) {
					uni.showToast({
						icon: 'none',
						title: '未登录或登录状态已超时',
						duration: 1500
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/user/user',
						});
					}, 1500)
				}
			},
			fail: (err) => {
				console.log('request fail', err)
				uni.showToast({
					icon: 'none',
					title: 'Promise err',
					duration: 2000
				});
				reject(res)
			}
		})
	})
}

  export暴露后,因为请求多个页面都会调用,在每个页面import上太麻烦了,决定直接挂载在vue上

在main.js中

import { urlRequest } from './common/url.js'
Vue.prototype.$urlRequest = urlRequest

页面中的使用

this.$urlRequest('/login', this.param, 'post').then(res => {
	if (res.data.success) {
		this.$store.commit('login', res.data.data)
		this.$urlRequest('获取用户信息').then(res => {
			if (res.data.success) {
				this.$store.commit('getUserInfo', res.data.data)
					uni.showToast({
						title: '登录成功',
						duration: 1500
					});
					setTimeout(() => {
						uni.reLaunch({
						               url: '/pages/user/user',
						});
					}, 1500)
			} else {
				uni.showToast({
					icon: 'none',
					title: res.data.msg,
					duration: 1500
				});
			}
		})
	} else {
		uni.showToast({
			icon: 'none',
			title: res.data.msg,
			duration: 2000
		});
	}
})

  

猜你喜欢

转载自www.cnblogs.com/Mijiujs/p/12096199.html