1.新建一个request.js文件
var app = getApp();
const baseUrl = '请求头地址';
// 调接口方法
const fetchData = (url, data, method, callback, errCallback) => {
wx.showLoading();
let token = wx.getStorageSync('$$token')
wx.request({
url: baseUrl + url,
header: {
'Authorization': token,
},
method: method,
data: data,
success: function (res) {
wx.hideLoading();
// token过期,跳到授权页面
if (res.data.code === 401) {
wx.reLaunch({
url: '/pages/login/login'
})
console.log('超时登录,tocken失效')
return;
}
if (res.data.code !== 200) {
if (errCallback) {
return errCallback(res);
}
wx.showToast({
title: res.data.msg,
icon: 'none'
});
return;
}
callback(res);
}
})
}
// 排除方法,在外面可调用
module.exports = {
fetchData: fetchData
}
2. 页面引入并调用,按照request里面定义的顺序传参即可
import {fetchData} from '../../utils/request'
fetchData('/api/knowledges', { pageNo: this.data.page, pageSize: this.data.pageSize },'GET', res => {
console.log(res) // 成功结果回调
}, err => {
})