微信小程序常用api 封装
/**
* 封封微信的的request
*/
function request(url, data = {}, method = "POST", header = "application/x-www-form-urlencoded") {
wx.showLoading({
title: '加载中...',
});
return new Promise(function (resolve, reject) {
wx.request({
url: url,
data: data,
method: method,
header: {
'Content-Type': header,
'X-Nideshop-Token': wx.getStorageSync('token')
},
success: function (res) {
wx.hideLoading();
if (res.statusCode == 200) {
if (res.data.errno == 401) {
wx.navigateTo({
url: '/pages/login/login',
})
} else {
resolve(res.data);
}
} else {
reject(res.errMsg);
}
},
fail: function (err) {
reject(err)
}
})
});
}
/**
* 检查微信会话是否过期
*/
function checkSession() {
return new Promise(function (resolve, reject) {
wx.checkSession({
success: function () {
resolve(true);
},
fail: function () {
reject(false);
}
})
});
}
/**
* 调用微信登录
*/
function login() {
return new Promise(function (resolve, reject) {
wx.login({
success: function (res) {
if (res.code) {
resolve(res);
} else {
reject(res);
}
},
fail: function (err) {
reject(err);
}
});
});
}
function showErrorToast(msg) {
wx.showToast({
title: msg,
image: '/static/images/icon_error.png'
})
}
function showSuccessToast(msg) {
wx.showToast({
title: msg,
})
}
function formatTime(date) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}