50 lines
1.3 KiB
JavaScript
50 lines
1.3 KiB
JavaScript
// utils/request.js
|
||
import config from '@/config';
|
||
|
||
export function request(options) {
|
||
// 在请求发送前做一些处理,如添加 token
|
||
const token = uni.getStorageSync('token');
|
||
|
||
options.header = options.header || {};
|
||
options.header['token'] = token;
|
||
options.header['content-type'] = 'application/x-www-form-urlencoded';
|
||
|
||
options.method = options.method || "POST";
|
||
options.url = config.apiUrl + options.url;
|
||
|
||
return new Promise((resolve, reject) => {
|
||
uni.request({
|
||
...options,
|
||
success: (response) => {
|
||
if (response.data.code == 10030) {
|
||
// 没有登录,跳转到登录页,并带上当前页面的URL
|
||
redirectToLoginWithRedirect();
|
||
} else {
|
||
resolve(response);
|
||
}
|
||
},
|
||
fail: (error) => {
|
||
reject(error);
|
||
},
|
||
});
|
||
});
|
||
}
|
||
|
||
function redirectToLoginWithRedirect() {
|
||
let currentRoute = '';
|
||
// 获取当前页面路径和参数
|
||
const pages = getCurrentPages();
|
||
if (pages.length) {
|
||
const currentPage = pages[pages.length - 1];
|
||
currentRoute = currentPage.route;
|
||
const query = Object.keys(currentPage.options)
|
||
.map(key => `${key}=${currentPage.options[key]}`)
|
||
.join('&');
|
||
if (query) currentRoute += '?' + query;
|
||
}
|
||
|
||
// 重定向到登录页面
|
||
uni.redirectTo({
|
||
url: `/pages/login/login?redirect=${encodeURIComponent(currentRoute)}`,
|
||
});
|
||
} |