mini/api/request.js
2025-04-13 01:27:54 +08:00

140 lines
3.2 KiB
JavaScript
Raw 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.

// 全局API请求实例
class Request {
constructor() {
this.baseURL = 'https://meida-api.beefast.co';
this.interceptors = {
request: [],
response: []
};
this.setupInterceptors();
}
setupInterceptors() {
// 添加请求拦截器
this.addRequestInterceptor(config => {
// 在这里添加通用的请求头如token等
const token = wx.getStorageSync('token');
if (token) {
config.header = {
...config.header,
'Authorization': `Bearer ${token}`
};
}
return config;
});
// 添加响应拦截器
this.addResponseInterceptor(response => {
// 处理通用的响应逻辑
if (response.statusCode === 401) {
if(this.loginRoutePromise){
throw new Error(response.data)
}
const pages = getCurrentPages();
const currentPages = pages[pages.length-1];
if(currentPages&&currentPages.route.indexOf('pages/my/login/index')>-1){
throw new Error('已在登录页面');
}
// token过期重新登录
this.loginRoutePromise = wx.navigateTo({
url: '/pages/my/login/index'
});
this.loginRoutePromise.then(()=>{
this.loginRoutePromise = null;
})
throw new Error(response.data)
}
return response;
});
}
addRequestInterceptor(interceptor) {
this.interceptors.request.push(interceptor);
}
addResponseInterceptor(interceptor) {
this.interceptors.response.push(interceptor);
}
async processRequestInterceptors(config) {
for (const interceptor of this.interceptors.request) {
config = await interceptor(config);
}
return config;
}
async processResponseInterceptors(response) {
for (const interceptor of this.interceptors.response) {
response = await interceptor(response);
}
return response;
}
async request(config) {
try {
config = await this.processRequestInterceptors(config);
const url = config.url.startsWith('http') ? config.url : `${this.baseURL}${config.url}`;
return new Promise((resolve, reject) => {
wx.request({
...config,
url,
success: async (res) => {
try {
const processedResponse = await this.processResponseInterceptors(res);
resolve(processedResponse.data.data);
} catch (error) {
reject(error);
}
},
fail: (error) => {
reject(error);
}
});
});
} catch (error) {
throw error;
}
}
get(url, params, options = {}) {
return this.request({
method: 'GET',
url,
data: params,
...options
});
}
post(url, data, options = {}) {
return this.request({
method: 'POST',
url,
data,
...options
});
}
put(url, data, options = {}) {
return this.request({
method: 'PUT',
url,
data,
...options
});
}
delete(url, data, options = {}) {
return this.request({
method: 'DELETE',
url,
data,
...options
});
}
}
// 创建全局请求实例
const request = new Request();
export default request;