基于mpvue微信小程序 promise+wx.request 封装请求

第一步:

在微信小程序中引入es6-promise

如果是基于mpvue框架进行微信小程序开发,只需要

npm install es6-promise

第二步:

在项目中创建一个utils文件夹,主要用来装一些用到的工具

然后再utils下面创建一个requet.js

const Promise = require('es6-promise').Promise

function wxPromisify(fn) {
	return function(obj = {}) {
		return new Promise((resolve, reject) => {
			obj.success = function(res) {
				//成功 (只返回res.data)
				resolve(res.data)
			}
			obj.fail = function(res) {
				//失败
				reject(res)
			}
			fn(obj)
		})
	}
}
//无论promise对象最后状态如何都会执行
Promise.prototype.finally = function(callback) {
	let P = this.constructor;
	return this.then(
		value => P.resolve(callback()).then(() => value),
		reason => P.resolve(callback()).then(() => {
			throw reason
		})
	);
};
/**
 * 微信请求get方法
 * url
 * data 以对象的格式传入
 */
function getRequest(url, data) {
	var getRequest = wxPromisify(wx.request)
	return getRequest({
		url: url,
		method: 'GET',
		data: data,
		header: {
			'Content-Type': 'application/json'
		}
	})
}

/**
 * 微信请求post方法封装
 * url
 * data 以对象的格式传入
 */
function postRequest(url, data) {
	var postRequest = wxPromisify(wx.request)
	return postRequest({
		url: url,
		method: 'POST',
		data: data,
		header: {
			"content-type": "application/x-www-form-urlencoded"
		},
	})
}

/**
 * 获取get的URL
 */
function getRquestUrl(url, data) {
	var signArr = [];
	for(var x in data) {
		var sign = x + '=' + data[x];
		signArr.push(sign)
	}

	var signString = '';
	for(var x in signArr) {
		if(parseInt(x) + 1 == 1) {
			signString += signArr[x].toString();
		} else {
			signString += "&" + signArr[x].toString();
		}
	}
	return url + "?" + signString;
}

/*文件上传*/
function uploadFile(url,files,name,data) {
	return new Promise((resolve, reject) => {
		wx.uploadFile({
			url: url,
			filePath: files,
			name: name,
			formData: data,
			success: (res => {
				if(res.statusCode === 200) {
					//200: 服务端业务处理正常结束
					resolve(res)
				} else {
					reject(res)
				}
			}),
			fail: (res => {
				reject(res)
			})
		})
	})
}

module.exports = {
	postRequest: postRequest,
	getRequest: getRequest,
	getRquestUrl: getRquestUrl,
	uploadFile:uploadFile
}

第三步:

在utils文件夹中 ,新建一个api.js文件,主要用来装请求的接口

import requestAll from './request' // 此处,引入存放对promise处理的文件

const apiUrl = '域名' 
const webUrl = '域名'

class api {

//首页分享
	indexShare(session,language){
		let data = {
			session,
			language
		}
		return requestAll.postRequest(apiUrl + 'portal/index/wechat_share', data);
	}

}

//暴露接口
export default {
	api:api
}

第四步:

在主文件main.js中 添加api属性 (这里设置才可以在页面中使用)

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

Vue.config.productionTip = false
App.mpType = 'app'

import Vuex from 'vuex'
Vue.use(Vuex)

import api from './utils/api'
Vue.prototype.$api = api

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

第五步:

在页面中引用

由于mpvue不可以像vue那样直接 this.$api拿到暴露的接口属性

需要this.$api.api.prototype 才可以拿到api中定义的funciton

<script>


	export default {
		data() {
			return {
				Request: this.$api.api.prototype, //请求头
			}
		},

		methods: {
                    
		    indexShare(){
			var that  = this;
			that.Request.indexShare('参数1','...')
					.then(res =>{
                                                //成功
//						console.log(res)
						
					})
					.catch(res =>{
                                                //失败
						console.log(res)
					})
                    }
       }
</script>

这样就可以用promise封装wx.request请求后端接口了,谢谢! 不喜勿喷!

猜你喜欢

转载自blog.csdn.net/qq_34322905/article/details/83149699