小程序接口封装
封装接口文件 api.js
// 服务器地址
const host = 'https://xxx.com';
// 请求接口
const apiLogin = host+'Passport/login';
const apiIndexOrder = host+'Index_order/index';
const apiOrderList = host+'Index_order/list';
//通用请求接口方法
const apiRequest = (url,data={},callback,method="post", header) => {//接收所需要的参数,如果不够还可以自己自定义参数
wx.request({
url: url,
data: data ? data : null,
method: method,
header: header ? header : { 'content-type':'application/x-www-form-urlencoded'},
success: function (res) {
//接口调用成功
//根据业务需要 返回的json的数据
console.log('api请求成功')
console.log(res.data)
return typeof callback == "function" && callback(res.data)
},
fail: function (res) {
// fail调用接口失败
return typeof callback == "function" && callback(false)
}
})
}
通用图片请求接口方法
// 上传图片
const apiUpload = (url,filePath,callback)=>{
wx.uploadFile({
filePath: filePath,
name: 'file',
url: url,
success:function (res) {
console.log('上传图片成功')
console.log(JSON.parse(res.data))
return typeof callback == "function" && callback(JSON.parse(res.data))//返回图片地址
},
fail:function (res) {
return typeof callback == "function" && callback(false)
}
})
}
//登录接口
const login = (data,callback)=>{
apiRequest(apiLogin,data,function(res){
return typeof callback == "function" && callback(res)
})
}
// 订单
const indexOrder = (data,callback)=>{
apiRequest(apiIndexOrder, data,function(res){
return typeof callback == "function" && callback(res)
});
}
//流水列表
const orderList = (data,callback)=>{
apiRequest(apiOrderList, data,function(res){
return typeof callback == "function" && callback(res)
});
}
上传图片接口
const uploadImg = (callback)=>{
wx.chooseImage({
count:1,
success(res){
let filePath = res.tempFilePaths[0];
apiUpload(apiUploadImg,filePath,function(res){
return typeof callback == "function" && callback(res)
});
}
})
}
接口模块化
module.exports = {
login,
indexOrder,
orderList,
uploadImg
}
调用api方法
const api = require("文件位置");
例:
const api = require("../../utils/api.js");
//引用方法
let data = [];
api.indexOrder(data,function(res){
console.log(“请求结果”)
if(res.code == 200){
// ...
}
}