【uni app】用promise封裝uni.request


原生的uni.requestAPI有promise形式,網上也有uni-request封裝模仿axios(我在調用的時候出了問題,還沒找到原因)

在基於以下情況決定自己封裝

  1. 有baseUrl
  2. 有時請求header中的content-type 為 application/x-www-form-urlencoded
  3. 登錄后調用接口header中需要塞token
  4. 在調用接口前對數據可以進行統一處理,比如刪除值為null的屬性
  5. 在調用接口后某些數據屬性為null,在uni app中template里放值為null的屬性會顯示undefined,可以統一轉成無數據
  6. 加載狀態(?感覺有點不合理,用promise.all解決好像更好)

在項目目錄static的js文件下的新建url.js

function request(url, data, method = 'get', contentType = 1) {
	let header = {
		'content-type':contentType === 1 ? 'application/json' : 'application/x-www-form-urlencoded',
		Authorization:uni.getStorageSync('authorization') != ''?uni.getStorageSync('authorization'):null
	}
	for (let property in data) {
		if (data[property] == null) {
			delete data[property]
		}
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			data,
			method,
			header,
			success: (res) => {
				if (res.statusCode == 200) {
					resolve(res)
				} else if (res.statusCode == 405) {
					uni.showToast({
						icon: 'none',
						title: '請求方法錯誤',
						duration: 1500
					});
				} else if (res.statusCode == 401) {
					uni.showToast({
						icon: 'none',
						title: '未登錄或登錄狀態已超時',
						duration: 1500
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/me/user/user',
						});
					}, 1500)
					store.commit('logout')
				} else {
					uni.showToast({
						icon: 'none',
						title: '請求錯誤:' + res.statusCode,
						duration: 1500
					});
				}
			},
			fail: (err) => {
				console.log('request fail', err)
				uni.showToast({
					icon: 'none',
					title: err.errMsg,
					duration: 2000
				});
				reject(err)
			}
		})
	})
}

export暴露后,在main.js中直接掛載在vue上

import { request, urlList } from './common/url.js'
Vue.prototype.$http= request
Vue.prototype.$urlList = urlList

頁面中的使用:

this.$http(this.$urlList.login, param, 'post').then(res => {
	if (res.data.success) {
		
	} else {
		
	}
})

如果content-type有其他的自己在方法中配置其他的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM