我是封装在uilts文件夹下,尽量减少文件数量;
/**
* 自定义post函数,返回Promise
* +-------------------
* author: 李先生<17638198892@163.com>
* +-------------------
* @param {String} url 接口网址
* @param {arrayObject} data 要传的数组对象 例如: {name: '李先森', age: 24}
* +-------------------
* @return {Promise} promise 返回promise供后续操作
*/
function reqHttps(reqUrl, reqData, reqType){
var promise = new Promise((resolve, reject) => {
//init
var that = this;
/*
//自动添加签名字段到postData,makeSign(obj)是一个自定义的生成签名字符串的函数
postData.signature = that.makeSign(postData);
*/
//网络请求
wx.request({
url: reqUrl,
data: reqData,
method: reqType,
header: {
'content-type': 'application/json',
'X-Bmob-Application-Id': 'd4541dd59bbc2dbd626201672d5c69ca',
'X-Bmob-REST-API-Key': '80c7719eefed932aacb29bd5dbda4925'
},
success: function (res) {//服务器返回数据
if (res.statusCode == 200) {//res.data 为 后台返回数据,格式为{"data":{...}, "info":"成功", "status":1}, 后台规定:如果status为1,既是正确结果。可以根据自己业务逻辑来设定判断条件
resolve(res.data.results);
} else {//返回错误提示信息
reject(res);
}
},
error: function (e) {
reject('网络出错');
}
})
});
return promise;
}
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
module.exports = {
formatTime: formatTime,
reqHttps: reqHttps
}
在调用页面引入 uilts
index.js
var myHttps = require('../../utils/util.js');
myHttps.reqHttps('https://api2.bmob.cn','','GET').then((res) => {
console.log('封装后的数据',res)
}).catch((errMsg)=>{
console.log(errMsg)
})
完成!