feat: 封装js
parent
f5ab55c4bc
commit
a171926318
|
@ -1,69 +0,0 @@
|
||||||
import type { RequestClientOptions } from '@vben/request';
|
|
||||||
|
|
||||||
import { useAppConfig } from '@vben/hooks';
|
|
||||||
import { defaultResponseInterceptor, RequestClient } from '@vben/request';
|
|
||||||
|
|
||||||
import { useTokenStore } from '#/store'; // cc:增加token存储
|
|
||||||
|
|
||||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
|
||||||
|
|
||||||
function createCDCMRequestClient(
|
|
||||||
baseURL: string,
|
|
||||||
options?: RequestClientOptions,
|
|
||||||
) {
|
|
||||||
const client = new RequestClient({
|
|
||||||
...options,
|
|
||||||
baseURL,
|
|
||||||
});
|
|
||||||
|
|
||||||
client.addResponseInterceptor(
|
|
||||||
defaultResponseInterceptor({
|
|
||||||
codeField: 'code',
|
|
||||||
dataField: 'data',
|
|
||||||
successCode: 0,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
// 响应拦截器:自动更新 token
|
|
||||||
client.addResponseInterceptor({
|
|
||||||
fulfilled: (response) => {
|
|
||||||
const token = response.headers?.token;
|
|
||||||
if (token) {
|
|
||||||
// 如果响应头中有新 token,自动更新 store
|
|
||||||
useTokenStore().setToken(token);
|
|
||||||
}
|
|
||||||
return response;
|
|
||||||
},
|
|
||||||
rejected: (error) => {
|
|
||||||
// 统一错误处理(如 token 过期)
|
|
||||||
if (error.response?.status === 401) {
|
|
||||||
useTokenStore().deleteToken();
|
|
||||||
// 这里要跳登录页面
|
|
||||||
}
|
|
||||||
return Promise.reject(error);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// 请求拦截器:自动添加 token
|
|
||||||
client.addRequestInterceptor({
|
|
||||||
fulfilled: (config) => {
|
|
||||||
const token = useTokenStore().token;
|
|
||||||
if (token) {
|
|
||||||
// 添加 CDCM 自定义头部
|
|
||||||
config.headers.set('cdcm', token, true);
|
|
||||||
}
|
|
||||||
return config;
|
|
||||||
},
|
|
||||||
rejected: (error) => {
|
|
||||||
// 请求错误处理
|
|
||||||
return Promise.reject(error);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return client;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const cdcmRequestClient = createCDCMRequestClient(apiURL);
|
|
||||||
|
|
||||||
export async function cdcmTemplateAPI(params: any) {
|
|
||||||
return cdcmRequestClient.post('/api/v1/cdcm', params);
|
|
||||||
}
|
|
Loading…
Reference in New Issue