网络请求封装
class Req {
baseUrl;
header;
instence;
timeout;
constructor(config) {
this.baseUrl = config.baseUrl;
this.header = config.header;
this.timeout = config.timeout;
}
request(config) {
return new Promise((resove, reject) => {
this.header.Authorization = wx.getStorageSync("token");
wx.showLoading();
wx.request({
url: this.baseUrl + config.url,
data: config.data,
header: config.header || this.header,
method: config.method,
timeout: this.timeout,
success: (res) => {
// 返回了错误信息
if (res.data.err_code != 200) {
// 未登录
if (res.data.err_code == 401) {
wx.showToast({
title: "请先登录",
icon: "error",
});
} else if (res.data.err_code == 403) {
//没有权限
wx.showToast({
title: "没有权限",
icon: "error",
});
} else {
wx.showToast({
title: res.data.msg,
icon: "error",
});
}
}
resove(res.data);
},
fail: (err) => {
wx.showToast({
title: "接口请求失败",
icon: "error",
});
reject(err.errMsg);
},
complete() {
wx.hideLoading();
},
});
});
}
}
const request = new Req({
baseUrl: "http://192.168.31.100:209/api",
timeout: 10000,
header: {},
});
// config包含url,data,method,header?
const useRequest = (config) => {
return request.request({
...config,
});
};
const useGet = (url = "", data = {}) => {
return request.request({
url,
data,
method: "GET",
});
};
const usePost = (url = "", data = {}) => {
return request.request({
url,
data,
method: "POST",
});
};
export { useRequest, useGet, usePost };
onlaunch和onload的异步问题
app.js中的函数和变量可以使用getApp().name访问到
在onload需要获取数据的地方,判断可不可以访问到数据,如果不可以,getApp().callback=(data)=>{}。
在onlaunch中异步获取数据后,判断this.callback&&this.callback(data),this.callback=null
或者可以使用Promise
// app.js
onLaunch () {
wx.login({
success: result => {
wx.request({
method: ''
url: '' // 示例
data: {...},
success: res => {
this.globalData.openId = res.data.openId
// 回调
if (this.callback) callback(res.data)
this.callback=null
},
fail: err => {
// 需要的话请求失败处也可以使用回调
}
})
}
})
}
// page.js
onLoad () {
const app = getApp()
if (app.globalData.openId) {
// do something
} else {
app. callback = (data) => {
// do something
}
}
}