小程序requestUtil工具類
1.前言
開發小程序已經有一段時間了,都沒有寫過小程序相關的文章,踩過坑挺多,把這些坑記下來,下次就不會再犯了。
小程序自帶的請求方法不是特別方便,無意中得到了一個工具類,因此把這個工具類分享出來
2.工具類詳情
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
}
//添加請求根目錄
var rootDocment = 'https://yjt.*****.com/wechat';
function req(url, data, cb) {
wx.request({
url: rootDocment + url,
data: data,
method: 'post',
header: { 'Content-Type': 'application/x-www-form-urlencoded' },
success: function (res) {
return typeof cb == "function" && cb(res.data)
},
fail: function () {
return typeof cb == "function" && cb(false)
}
})
}
function getReq(url, data, cb) {
wx.request({
url: rootDocment + url,
data: data,
method: 'get',
header: { 'Content-Type': 'application/x-www-form-urlencoded' },
success: function (res) {
return typeof cb == "function" && cb(res.data)
},
fail: function () {
return typeof cb == "function" && cb(false)
}
})
}
// 去前后空格
function trim(str) {
return str.replace(/(^\s*)|(\s*$)/g, "");
}
// 提示錯誤信息
function isError(msg, that) {
that.setData({
showTopTips: true,
errorMsg: msg
})
}
// 清空錯誤信息
function clearError(that) {
that.setData({
showTopTips: false,
errorMsg: ""
})
}
function formatTime(time) {
var year = time.getFullYear();
var month = time.getMonth() + 1;
var date = time.getDate();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}
module.exports = {
formatTime: formatTime,
req: req,
trim: trim,
isError: isError,
clearError: clearError,
getReq: getReq,
formatTime: formatTime
}
3.用法
在page頁面頂部定義
var wechatUtil = require('../../utils/wechatRequest.js');
發起請求
wechatUtil.req("/member/update",{
"unionId": unionId,
"username": username,
"headImg": headImg
},function(res){
//res為返回的數據
if(res.resultCode == 200){
console.log("更新用戶信息成功");
console.log(res);
// that.setData({
// member:res.resultContent
// });
}else{
console.log("更新用戶信息失敗");
console.log(res);
}
})
4.結尾
好了,一個簡單的工具類結束了,拜拜

浙公網安備 33010602011771號