不管做什么项目,一般会对ajax请求做个二次封装,小程序也不例外。
小程序开发中都会调用API,小程序的开发文档提供了相对实用的api
wx.request(),把它进行二次封装成自己喜欢的写法// 后端接口服务地址 var serverUrl = 'https://*************';
封装方法
request(url, method, params) {
let header = {
'token': wx.getStorageSync("token"),
'sessionKey': wx.getStorageSync("sessionkey")
}
let userurl = serverUrl +url
}
return new Promise((resolve, reject) => {
wx.request({
url: userurl,
method: method,
data: data,
header: header,
success: function(res) {
if (res.statusCode == 200) {
resolve(res);
}else if (res.statusCode == '401'){
wx.redirectTo({
url: '/pages/login/login', //跳转到登录页
})
reject(res.data);
} else {
reject(res.data);
}
},
fail: (res => {
console.log(res)
wx.hideLoading();
wx.showToast({
title: '网络差,请稍后再试!',
icon: 'none',
duration: 1500
})
reject('网络差,请稍后再试!');
})
})
})
},
在需要的地方引入
const app = getApp()
Page({
app.request(url,method,params).then(res=>{
console.log(res)
})
})