94 lines
2.2 KiB
TypeScript
94 lines
2.2 KiB
TypeScript
![]() |
import { useMemberStore } from "@/store/modules/member";
|
|||
|
import ENV_CONFIG from "../config/env";
|
|||
|
|
|||
|
|
|||
|
// 基础地址
|
|||
|
let baseUrl = "";
|
|||
|
// #ifdef H5
|
|||
|
(process.env as any).config= ENV_CONFIG
|
|||
|
// #endif
|
|||
|
|
|||
|
baseUrl = (process.env as any).config[(process.env as any).NODE_ENV]
|
|||
|
.VITE_APP_BASE_URL;
|
|||
|
|
|||
|
|
|||
|
const store = useMemberStore();
|
|||
|
|
|||
|
const obj = {
|
|||
|
// 拦截前触发
|
|||
|
invoke(options: UniApp.RequestOptions) {
|
|||
|
// 超时时间
|
|||
|
options.timeout = 10000;
|
|||
|
// 拼接完整路径
|
|||
|
if (!options.url.startsWith("http")) {
|
|||
|
options.url = baseUrl + options.url;
|
|||
|
}
|
|||
|
// 请求头标识
|
|||
|
// 1.小程序唯一标识
|
|||
|
// 'source-client': 'miniapp'
|
|||
|
options.header = { ...options.header };
|
|||
|
options.header["source-client"] = "miniapp";
|
|||
|
// 2.注入token
|
|||
|
// 2.1 获取token
|
|||
|
const token = store.profile?.token;
|
|||
|
if (token) {
|
|||
|
options.header["x-userToken"] = token;
|
|||
|
}
|
|||
|
},
|
|||
|
};
|
|||
|
// 请求拦截器
|
|||
|
uni.addInterceptor("request", obj);
|
|||
|
uni.addInterceptor("uploadFile", obj);
|
|||
|
|
|||
|
interface Data<T> {
|
|||
|
code: string | number;
|
|||
|
data: T;
|
|||
|
msg: string;
|
|||
|
result: T;
|
|||
|
message: string;
|
|||
|
}
|
|||
|
// 响应拦截器
|
|||
|
/***
|
|||
|
* 1001: 未登录
|
|||
|
* 1002: 登陆过期
|
|||
|
*/
|
|||
|
export const http = <T>(options: UniApp.RequestOptions) => {
|
|||
|
return new Promise<Data<T>>((resolve, reject) => {
|
|||
|
uni.request({
|
|||
|
...options,
|
|||
|
success(res) {
|
|||
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|||
|
if (
|
|||
|
(res.data as any).code === 1001 ||
|
|||
|
(res.data as any).code === 1002
|
|||
|
) {
|
|||
|
uni.showToast({
|
|||
|
icon: "none",
|
|||
|
title: (res.data as Data<T>).message || "请求失败",
|
|||
|
});
|
|||
|
store.clearProfile();
|
|||
|
// uni.navigateTo({
|
|||
|
// url: "/pages/login/index",
|
|||
|
// });
|
|||
|
return;
|
|||
|
}
|
|||
|
resolve(res.data as Data<T>);
|
|||
|
} else {
|
|||
|
uni.showToast({
|
|||
|
icon: "none",
|
|||
|
title: (res.data as Data<T>).msg || "请求失败",
|
|||
|
});
|
|||
|
reject(res);
|
|||
|
}
|
|||
|
},
|
|||
|
fail(err) {
|
|||
|
uni.showToast({
|
|||
|
icon: "none",
|
|||
|
title: "网络错误,请检查网络",
|
|||
|
});
|
|||
|
reject(err);
|
|||
|
},
|
|||
|
});
|
|||
|
});
|
|||
|
};
|