封装使用uniapp开发微信小程序的ajax请求

一、使用uni.request方法和Promise进行封装,代码如下:

let Promises = Promise
import config from './config'  //这是我存放接口api的文件
const host = config.host;  //这是获取域名
Promises.prototype.finally = function(callback) {
   let P = this.constructor
   return this.then(
       value => P.resolve(callback()).then(() => value),
       reason => P.resolve(callback()).then(() => {
          throw reason
    }))
}
class Https {
	host(){
		return config.host
	}
    request (url, method, data) {
		const cachekey = uni.getStorageSync('cachekey')  //获取用户登录的cachekey或者token
		return new Promises((resolve, reject) => {
		  uni.request({
			url: host + url, 
			method: method,
			data: {
				clientID:1,  //开发用到的clientID
				AuthKey:'1', //开发用到的AuthKey
				...data,
				'cachekey':  cachekey || ''
			},
			header: {
			  'content-type': 'application/x-www-form-urlencoded' ,// 默认值
			},
			success: function (res) {
				if(res.statusCode == 200){
					resolve(res.data)
				} else{
					resolve(res.data)
				}
			},
			fail: function (error) {
			  reject(error)
			}
		  })
		})
	}
	upLoad(params) { //上传文件图片等
		uni.showLoading({
			title: '正在上传'
		})
		const cachekey = uni.getStorageSync('cachekey')
		return new Promises((resolve, reject) => {
			uni.uploadFile({
				url: host + '/api/UserCenter/Account/ImgUpload',  
				filePath: params.path,
				formData: {
					'cachekey': cachekey,
					clientID:1,
					AuthKey:'1',
				},
				name: params.name || 'img',
				success: function (res) {
					resolve(res.data)
					uni.hideLoading()
				},
				fail: function (error) {
					reject(error)
					uni.hideLoading()
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				}
		 })
		})
	}
    get (url, data) {
       return this.request(url, 'GET', data)
    }
    post (url, data) {
       return this.request(url, 'POST', data)
    }
    uniApi(params, data) {
		return new Promises((resolve, reject) => {
		  params.events({
			...data,
			success (res) {
			  resolve(res)
			},
			fail(err) {
			  reject(err)
			}
		  })
		})
    }
}
const https = new Https()
export default https

二、使用方法

1、在main.js添加如下代码

import https from './util/api.js'
Vue.prototype.$http = https
Vue.prototype.$api = api

2、在需要的文件中直接使用即可:

onShow(){
   //今日好券
   this.$http.get(this.$api.GetThirdPartyBusinessCouponList, {top: 3}).then((res) => {
		if (res.StatusCode == '10000000') {
			this.quanData = res.Data;
		}
	})
}

你可能感兴趣的:(封装使用uniapp开发微信小程序的ajax请求)