utils文件下创建api.js
const apiRequest = (url, method, data) => {
const app = getApp()
//接收所需要的参数,如果不够还可以自己自定义参数
let promise = new Promise(function (resolve, reject) {
var api ='http://localhost:3000'
wx.request({
url: api+url,
data: data ? data : null,
method: method,
header: { 'authorization': wx.getStorageSync('eletoken') },
success: function (res) {
if (res.data.status == "401") {
wx.removeStorageSync('eletoken');
wx.request({
url: api+'/users/refreshToken',
//服务器的地址,现在微信小程序只支持https请求,所以调试的时候请勾选不校监安全域名
header: {
'content-type': 'application/json'
},
method: "GET",
success: function (res) {
wx.setStorageSync('eletoken', res.data.token);
apiRequest(url, method, data)
}
})
} else {
resolve(res);
}
//接口调用成功
//根据业务需要resolve接口返回的json的数据
},
fail: function (res) {
// fail调用接口失败
reject({ errormsg: '网络错误,请稍后重试', code: -1 });
}
})
});
return promise; //注意,这里返回的是promise对象
}
module.exports = apiRequest
页面count.js中引入api.js,并使用
var apiRequest = require('../../utils/http.js')
getAllByYesterday: function() {
var that = this;
apiRequest('/getAllByYesterday', 'GET', {
printDate: that.data.date,
workName: this.data.currentCenter
}).then(res => {
if (res.data.status == "404") {
wx.showToast({
title: res.data.msg,
icon: "none",
duration: 2000,
})
var data = res.data.result
that.setData({
countP: [],
countN: [],
displayP: 'block',
displayN: 'block'
})
return;
}
var data = res.data.result
var countP = []
var countN = []
data.forEach(item => {
if (item.categroy == '打印机') {
countP.push(item)
} else {
countN.push(item)
}
that.setData({
countP: countP,
countN: countN,
displayP: 'block',
displayN: 'block'
})
})
})
}