原本用法
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
method:“POST”,
data: { },
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data)
},
fail(err){
}
})
小曲封装
// 优化方案:对于某些接口(例如不需要登录),可以进行请求拦截,减少服务器请求次数
// 封装网络请求的方法,结合promise
const app = getApp()
module.exports = (url, data, type = 0) => {
// 小接口不走加载中提示框
// 优化方案:可以使用白名单,Map方法处理特殊的接口
if (url == "circle/addUserLike" || url == 'circle/delUserLike' || url == 'circle/addUserCollect' || url == 'circle/delUserCollect' || url == 'circle/addUserAttention' || url == 'circle/delUserAttention' || url == 'user/selectVerificationCode' || url == 'user/sendCode' || url == 'user/clearOnecollect' || url == 'user/goodsCollectionlist' || url == 'user/addressDel' || url == 'user/addressList' || url == 'user/sureOrder' || url == 'goods/addGoodsCollect' || url == 'goods/delGoodsCollect' || url == 'goods/addGoodsRemind' || url == 'goods/addGoodsBidLog') {
} else {
wx.showLoading({
title: '加载中...'
});
}
// 返回一个promise实例
return new Promise((resolve, reject) => {
// 不止一个域名
// 优化方案:可以封装两个方法,
let href
if (type) {
href = 'http://auction.dlpm.net.cn/api/' //PHP域名
} else {
href = 'http://sale.dlpm.net.cn/' //Java域名
}
// 小程序请求
wx.request({
url: href + url,
data: data,
header: {
'content-type': 'application/x-www-form-urlencoded',
'token': wx.getStorageSync('token'),
// 'token': '1234567'
},
method: "POST",
success(res) {
console.log(res.data);
if (res.statusCode == 200) {
// 登录过期,返回-1,正常返回1,错误返回0
if (res.data.result == -1) {
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo;
if (app.userInfoReadyCallback) {
app.userInfoReadyCallback(res)
}
}
})
wx.reLaunch({
url: '/pages/login/numberLogin/numberLogin',
})
} else {
wx.switchTab({
url: '/pages/my/my'
})
}
}
})
return;
} else if (res.data.result == 1) {
resolve(res.data.data);
} else if (res.data.result == 0) {
// 特殊的单独提醒
// if (url == "user/userLogin") {
// wx.showToast({
// title: '操作频繁,请稍后重试',
// icon: 'none',
// duration: 2000
// })
// } else{
// 解决错误信息弹窗一闪而过
wx.showLoading();
wx.hideLoading();
setTimeout(function () {
wx.showToast({
title: res.data.msg,
icon: 'none',
duration: 2000
})
}, 0)
// }
// reject(res.data); //可以传入失败回调
}
} else {
wx.showToast({
title: '接口请求失败,接口状态' + res.statusCode,
icon: 'none',
duration: 2000
})
}
},
fail() {
wx.showToast({
title: '接口调取失败,请检查网络连接',
icon: 'none',
duration: 2000
})
},
complete() {
wx.hideLoading();
}
})
})
}
调用index.js
// 优化方案:可以在app.js 中引入公共方法request,然后复制给wx对象
wx.request=request,然后即可全局访问
在页面里直接使用wx.http().then()即可
const http= require('../../utils/request.js');
wx.http=http
onload(){
http('/api/mobile/index.php?w=goods&t=goods_detail',{
goods_id: '100165'
}).then(data=>{
console.log(data) // 成功回调
wx.showToast({
title: '成功',
icon: 'none',
duration: 2000
})
}).catch(res=>{
console.log(res) //失败回调
}
)
}