1. 在 utils 文件中新建一个 request.js 文件
带登录验证
const apiHttp = " "; // 基本路径
// 请求方法
function request(url, method, data, header){
// 判断 是否有登录 token
data = data || {};
header = header || {};
let token = wx.getStorageSync("token");
let tokenHead = wx.getStorageSync("tokenHead");
if (token && tokenHead) {
if (!header || !header["Authorization"]) {
header["Authorization"] = tokenHead + token;
}
}
// 加载动画
wx.showLoading({
title: '加载中',
})
// 创建 promise 对象
let promise = new Promise((resolve, reject)=>{
wx.request({
url: apiHttp + url, // 地址
header: header,
data: data,
method: method,
success: function (res) {
wx.hideLoading() // 隐藏加载动画
// 判断是否成功(res的数据需要看接口返回的数据做判断)
if (typeof res.data === "object") {
if (res.data.code) {
// 判断是否有登录
if (res.data.code === 401) {
setTimeout(() => {
wx.redirectTo({
url: ' ', // 跳转登录页
})
}, 1000)
wx.showToast({
title: "请重新登录!",
icon: "none",
duration: 2000
});
} else if (res.data.code === 200){
resolve(res) // 请求成功
} else {
// 请求失败
wx.showToast({
title: res.data.message,
icon: "none",
duration: 2000
});
}
}
}
},
// 接口调用失败的回调函数
fail: function (res) {
wx.hideLoading()
wx.showToast({
title: '网络错误!',
icon: 'none',
duration: 2000
})
}
});
});
return promise;
}
// 对外暴露
module.exports = {
'get':function(url,data,header){
return request(url,"GET",data,header);
},
'post':function(url,data,header){
return request(url, "POST", data, header);
}
}普通封装
const apiHttp = " "; // 基本路径
// 请求方法
function request(url, method, data, header){
// 创建 promise 对象
let promise = new Promise((resolve, reject)=>{
wx.request({
url: apiHttp + url, // 地址
header: header,
data: data,
method: method,
success: function (res) {
resolve(res) // 请求成功
// 判断是否成功(res的数据需要看接口返回的数据做判断)
// if (res.data.status === 200){
// // 请求成功
// resolve(res)
// } else {
// // 请求失败
// wx.showToast({
// title: "错误!",
// icon: "none",
// duration: 2000
// });
// }
},
// 接口调用失败的回调函数
fail: function (res) {
wx.showToast({
title: '网络错误!',
icon: 'none',
duration: 2000
})
}
});
});
return promise;
}
// 对外暴露
module.exports = {
'get':function(url,data,header){
return request(url,"GET",data,header);
},
'post':function(url,data,header){
return request(url, "POST", data, header);
}
}
2. 在 app.js 中引入
// 引入
import request from './utils/request.js'
App({
onLaunch: function () {
// 在 app.js 中使用
this.request.get('')
.then(res => {
...
})
.catch(err => { console.log(err) })
},
// 注册
request
})3. 页面中使用
// 通过全局函数 getApp 可以获取全局的应用实例
const app = getApp()
// 调用
app.request.get('').then(res => {
console.log(res)
})
app.request.post('', { 参数 }).then(() => {
...
})
// Promise链式编程
app.request.get('')
.then(res => {
console.log(res)
})
.then(res => {
...
})
.then(res => {
...
})