一 . 在utils.js中新建getdata.js
二 . 在getdata.js中写入
//api地址
const apiurl = "(通用端口号)";
//优化,获取数据时显示提示
const pagedata = {
get(callback, url, data) {
const token = wx.getStorageSync('token') ? wx.getStorageSync('token') : ''; //判断Token
wx.showLoading({
title: '加载中...',
})
wx.request({
url: apiurl + url,
data: data,
method: 'GET',
header: {
'content-type': 'application/json', // 默认值
'Authorization': 'Bearer '+ token //在Authorization位置放置token
},
success: function (res) {
//隐藏提示
wx.hideLoading();
callback('success', res);
},
fail: function (err) {
console.log(err);
}
})
},
post(callback, url, data) {
const token = wx.getStorageSync('token') ? wx.getStorageSync('token') : '';
wx.showLoading({
title: '加载中...',
})
wx.request({
url: apiurl + url,
data: data,
method: 'POST',
header: {
'content-type': 'application/json', // 默认值
'Authorization': 'Bearer '+ token
},
success: function (res) {
//隐藏提示
wx.hideLoading();
callback('success', res);
},
fail: function (err) {
console.log(err);
}
})
}
}
//输出
module.exports = {
apidata: pagedata
}
三 . 写好后 在需要的页面顶部引入文件
四 . 在函数中使用
getdata.apidata.post((state, res) => {
if (state == 'success') {
console.log(res)
}
}, '/mbssale/api/agent/register',{
data
});