73 lines
2.1 KiB
TypeScript
73 lines
2.1 KiB
TypeScript
|
import { APIResponseErrorException } from '~/utils/APIResponse';
|
||
|
|
||
|
const fetch = $fetch.create({
|
||
|
onRequest(config) {
|
||
|
console.log('request config', config);
|
||
|
},
|
||
|
onResponse(context) {
|
||
|
const response = context.response;
|
||
|
console.log('响应数据:', response);
|
||
|
console.log('data:', response._data);
|
||
|
const data = response._data as APIResponse<unknown>;
|
||
|
if (data.code !== 200) {
|
||
|
if (data.code === 301 || data.code === 302) {
|
||
|
useRouter()
|
||
|
.push(
|
||
|
data.message && data.message.length > 0 ? data.message : '/login',
|
||
|
)
|
||
|
.then();
|
||
|
throw new APIResponseErrorException(data);
|
||
|
}
|
||
|
if (response.status === 401) {
|
||
|
useRouter().push('/login').then();
|
||
|
throw new APIResponseErrorException(data);
|
||
|
}
|
||
|
if (data.message && data.message.length > 0)
|
||
|
MessagePlugin.error(data.message).then();
|
||
|
throw new APIResponseErrorException(data);
|
||
|
}
|
||
|
if (data.message && data.message.length > 0)
|
||
|
MessagePlugin.success(data.message).then();
|
||
|
},
|
||
|
onResponseError({ response }) {
|
||
|
console.error('响应错误:', response);
|
||
|
// eslint-disable-next-line no-debugger
|
||
|
debugger;
|
||
|
// 在这里可以处理错误,例如跳转到登录页面或显示错误提示
|
||
|
},
|
||
|
});
|
||
|
export type HTTP = {
|
||
|
GET: <ReturnType>(
|
||
|
url: string,
|
||
|
records?: Record<string, string>,
|
||
|
) => Promise<APIResponse<ReturnType>>;
|
||
|
POST: <ReturnType>(
|
||
|
url: string,
|
||
|
body?: object,
|
||
|
) => Promise<APIResponse<ReturnType>>;
|
||
|
};
|
||
|
const baseURL = '/api';
|
||
|
export const $http: HTTP = {
|
||
|
GET: async <ReturnType>(url: string, records?: Record<string, string>) => {
|
||
|
url = baseURL + url;
|
||
|
const result: APIResponse<ReturnType> = await fetch(url, {
|
||
|
method: 'GET',
|
||
|
params: records,
|
||
|
});
|
||
|
return result;
|
||
|
},
|
||
|
POST: async <ReturnType>(url: string, body?: object) => {
|
||
|
url = baseURL + url;
|
||
|
const result: APIResponse<ReturnType> = await fetch(url, {
|
||
|
method: 'POST',
|
||
|
body: body,
|
||
|
});
|
||
|
return result;
|
||
|
},
|
||
|
};
|
||
|
|
||
|
export default defineNuxtPlugin((nuxtApp) => {
|
||
|
console.log('$http', $http);
|
||
|
nuxtApp.provide('http', $http);
|
||
|
});
|