promise封装请求后如何跳转?
因为封装请求后,每个接口都会返回登录态是否过期,通过判断登录态过期跳转至登录页,因为所有请求都要判断是否过期,想要在封装的请求里直接跳转,但封装的请求只能吐出,如果在返回里面写跳转就会报错,请问该怎么实现
3 回复
分享一个自己用的、自己封装的 request
/* 封装的 wx.request 请求
请求路径域名前缀 host 从 app.js 里面获取
data 转 JSON字符串 根据实际情况处理
请求头 header 从 app.js 里面获取
可根据实际使用情况在此处配置请求的加解密
*/
const app = getApp()
const request = (url, options) => {
var header = app.header;
return new Promise((resolve, reject) => {
wx.showLoading({
title: options.loadingText||"加载中",
mask: options.loadingMask||false
})
wx.request({
url: `${app.host}${url}`,
method: options.method,
data: options.data,
header: header,
success(request) {
wx.hideLoading();
/* 根据返回状态码判断返回数据 */
if (request.statusCode === 200) {
if (request.data.code === 1&&!options.hideModal) {
wx.showModal({
title: "警告",
content: request.data.msg,
showCancel: false
})
}
resolve(request.data);
} else if (request.statusCode === 401) {
wx.showModal({
title: "警告",
content: "XXXXXXXXXXXXXXX!",
showCancel: false,
success(){
wx.clearStorage();
wx.reLaunch({
url: "/pages/login/login"
})
}
})
} else if (request.statusCode === 429) {
wx.showToast({
title: "请求过于频繁!请不要多次重复刷新页面!",
icon: "none"
})
} else {
reject(request.data)
}
},
fail(error) {
wx.hideLoading();
reject(error.data)
}
})
})
}
const get = (url, options = {}) => {
return request(url, {
method: 'GET',
data: options.data,
loadingText: options.loadingText,
loadingMask: options.loadingMask,
hideModal: options.hideModal
})
}
const post = (url, options) => {
return request(url, {
method: 'POST',
data: options.data,
loadingText: options.loadingText,
loadingMask: options.loadingMask,
hideModal: options.hideModal
})
}
const put = (url, options) => {
return request(url, {
method: 'PUT',
data: options.data,
loadingText: options.loadingText,
loadingMask: options.loadingMask,
hideModal: options.hideModal
})
}
// 不能声明DELETE(关键字)
const remove = (url, options) => {
return request(url, {
method: 'DELETE',
data: options.data,
loadingText: options.loadingText,
loadingMask: options.loadingMask,
hideModal: options.hideModal
})
}
module.exports = {
get,
post,
put,
remove
}
/* Demo
options: {
loadingText: 请求loading界面显示的文字,默认‘加载中’
loadingMask: 请求遮罩,默认‘false’不遮罩
hideModal: 隐藏code为1时的modal弹框,默认‘false’不隐藏
}
import request from '../../utils/request'
request.post('login', {
data: {},
loadingText: "请求中"
}).then(res => {
if () {}
}).catch(err => {
wx.showToast({
title: err.message,
icon: 'none'
})
}) */