Files
CKB-mini-program/utils/request.js
2026-01-07 11:00:09 +08:00

50 lines
1.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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)}`,
});
}