在utils下面新建request.js文件
放下如下代码:
const $settings = require(’./settings.js’); //配置文件,配置域名和需要loading层的接口
const request = (method, url, data) => {
// 开启loading层
const loading = KaTeX parse error: Expected 'EOF', got '&' at position 67: …ue); loading &̲& wx.showLoadin…{KaTeX parse error: Expected 'EOF', got '}' at position 17: …ettings.httpUrl}̲{url}`,
method: method,
data: method == ‘POST’ ? data : data,
header: {
“Content-Type”: “application/x-www-form-urlencoded”,
‘Token’: wx.getStorageSync(‘token’) ?? ‘’
},
success(request) {
loading && wx.hideLoading();
if (request.data.code == 419) {
wx.showToast({
title: ‘请重新登录!’,
icon: ‘none’,
duration: 1000
})
wx.clearStorageSync();
wx.reLaunch({
url: “/pages/login/index”
});
return
}
resolve(request.data);
},
fail(error) {
reject(error.data)
}
})
})
}
module.exports = {
request
}
在settings.js里面放入
// 配置
module.exports = {
// 请求域名
httpUrl: ‘https://i.cnblogs.com/posts/edit’,
//需要加loading层的请求,防止重复提交
debounce: [“index/teamList”]
}
因为接口多,我做了更好的分类如(公共接口)
// 公共接口
const $request = require(’./request.js’);
const $pubilcApi = {
selectCompetitionList: (data) => $request.request(‘POST’, index/teamList
, data),//get方式不要data,改成GET
}
module.exports = {
$pubilcApi
}
新建api.js文件
const public_Api = require(’./public_api.js’).$pubilcApi;
module.exports = {
public_Api
}
在页面中使用
const _Request = require(’…/…/utils/api.js’);
_Request.public_Api.selectCompetitionList({
page: 1,
}).then(res => {
console.log(res)
})