微信小程序封装wx.request

在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)
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值