微信小程序的请求方法一直比较复杂,每次调用都要重写一遍,感觉效率很低,于是想简单封装一下,看起来美观一点点。
首先可以在小程序默认的utils/
文件夹下新建一个common.js
类,然后在common.js
里写上一些常用的方法。
比如封装一个网络请求,可以用这种
/*封装Post请求方法 */
function curl_post (url, data, resolve, reject) {
wx.request({
url: url,
data: data,
header: {
//'Content-Type': 'application/json'
'content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',
dataType: 'json',
responseType: 'text',
success: function (res) {
console.log("curl_post成功,返回结果:")
if (res.statusCode == 200) {
console.log(res.data)
resolve(res.data) // 成功回调
} else {
console.log(res)
resolve(res.errMsg)
}
},
fail: function (res) {
console.log("curl_post失败,返回结果:")
console.log(res)
reject(res)
},
complete: function (res) ,
})
}
默认是使用的Post方法,也可以增加一个参数变成GET,每次调用的时候,把url
和data
传进去,然后直接在回调函数里操作数据就可以。
调用示例:
var common = require("../../utils/common.js"); // 引入common方法,注意只能使用相对路径
// 执行调用
var PostUrl = "http://note.coccoo.cc"; // 要请求的url
var PostData = { name: "Mic" , age: 12 }; // 请求数据,使用json格式
// 发送请求
var app = getApp();
app.fnuo_post(PostUrl, PostData,
function(res){
// 请求成功后调用的函数,res为返回的数据
// 在这里做你想做的事
console.log(res);
},function(res){
// 请求失败调用的方法,可以弹出一些操作
console.log(res.errorMsg);
});
上传文件的方法与之类似,就不单独说了,只是要注意下上传文件后返回的数据默认是没有经过Json解析的
下面直接给出整个common.js
的示例:
/*封装Post请求方法 */
function curl_post (url, data, resolve, reject) {
wx.request({
url: url,
data: data,
header: {
//'Content-Type': 'application/json'
'content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',
dataType: 'json',
responseType: 'text',
success: function (res) {
console.log("curl_post成功,返回结果:")
if (res.statusCode == 200) {
console.log(res.data)
resolve(res.data) // 成功回调
} else {
console.log(res)
resolve(res.errMsg)
}
},
fail: function (res) {
console.log("curl_post失败,返回结果:")
console.log(res)
reject(res)
},
complete: function (res) ,
})
}
/* 封装Upload方法 */
function curl_upload(url, path, name, formData, resolve, reject){
wx.uploadFile({
url: url,
filePath: path,
name: name,
formData: formData,
success: function (res) {
var data = res.data
console.log("upload成功,返回结果:")
console.log(res) // 注意这里的res一般是字符串,没有经过json解析,需要你手动解析一遍
resolve(res)
}, fail: function (res) {
reject(res)
}
})
}
/* 时间戳转换时间 */
Date.prototype.format = function (format) {
var date = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S+": this.getMilliseconds()
};
if (/(y+)/i.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1
? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
}
}
return format;
}
// 这里是正式调用时间戳转时间的方法,可以修改format达到你想要的效果,或者直接
function timeToDate(timeStamp, format = 'yyyy-MM-dd') {
var timestamp3 = timeStamp;
var newDate = new Date();
newDate.setTime(timestamp3 * 1000);
return newDate.format(format);
}
// 错误信息提示框
function errorMsgDialog(msg){
wx.showToast({
// 失败原因
title: msg,
icon: "none",
})
}
// 正确信息提示框
function msgDialog(msg){
wx.showToast({
title: msg,
icon:"success",
})
}
module.exports.curl_post = curl_post
module.exports.curl_upload = curl_upload
module.exports.timeToDate = timeToDate
module.exports.msgDialog = msgDialog
module.exports.errorMsgDialog = errorMsgDialog
// var common = require('common.js')
// require 暂不支持绝对路径
比如我的目录是这样:
pages
index
- index.js
untils
- common.js
如果我想在index.js
中调用common.js
时,只能使用../../untils/common.js
这样相对路径来引用
调用示例:
var common = require("../../utils/common.js"); // 引入common方法
// 调用Post请求方法
var PostUrl = "http://note.coccoo.cc"; // 要请求的url
var PostData = { name: "Mic" , age: 12 }; // 请求数据,使用json格式
// 发送请求
app.fnuo_post(PostUrl, PostData,
function(res){
// 请求成功后调用的函数,res为返回的数据
// 在这里做你想做的事
console.log(res);
},function(res){
// 请求失败调用的方法,可以弹出一些操作
console.log(res.errorMsg);
});
// 调用上传文件方法,以上传图片做示例
// 调用小程序选择图片
wx.chooseImage({
success: function (res) {
var tempFilePaths = res.tempFilePaths
var UploadUrl = "http://note.coccoo.cc/upload"; // 你要上传到的地址
// 公共上传方法
app.curl_upload(UploadUrl, tempFilePaths[0], 'img', {},
function (res) {
var data = JSON.parse(res.data) // 一般需要解析json
common.msgDialog("上传成功");
},
function (res) {
common.errorMsgDialog(res.errorMsg);
}
);
}
})
以上
你这个 app 哪来的
小程序里面自带的,抱歉忘了声明,加上这句:var app = getApp();