feat: 修改统一request

This commit is contained in:
wangzhengkun 2022-08-11 14:14:55 +08:00
parent a56cad7220
commit 3456877000
5 changed files with 9 additions and 42 deletions

View file

@ -5,23 +5,13 @@ import { ResultData } from '@/api/interface';
import { ResultEnum } from '@/enums/httpEnum';
import { checkStatus } from './helper/checkStatus';
import { ElMessage } from 'element-plus';
import { GlobalStore } from '@/store';
import router from '@/routers';
/**
* pinia 使
* https://github.com/vuejs/pinia/discussions/971
* https://github.com/vuejs/pinia/discussions/664#discussioncomment-1329898
* https://pinia.vuejs.org/core-concepts/outside-component-usage.html#single-page-applications
*/
// const globalStore = GlobalStore();
import i18n from '@/lang';
const axiosCanceler = new AxiosCanceler();
const config = {
// 默认地址请求地址,可在 .env 开头文件中修改
baseURL: import.meta.env.VITE_API_URL as string,
// 设置超时时间10s
timeout: ResultEnum.TIMEOUT as number,
// 跨域时候允许携带凭证
withCredentials: true,
@ -30,25 +20,13 @@ const config = {
class RequestHttp {
service: AxiosInstance;
public constructor(config: AxiosRequestConfig) {
// 实例化axios
this.service = axios.create(config);
/**
* @description
* -> [] ->
* token校验(JWT) : token,vuex/pinia/
*/
this.service.interceptors.request.use(
(config: AxiosRequestConfig) => {
const globalStore = GlobalStore();
// * 将当前请求添加到 pending 中
axiosCanceler.addPending(config);
// * 如果当前请求不需要显示 loading,在 api 服务中通过指定的第三个参数: { headers: { noLoading: true } }来控制不显示loading参见loginApi
config.headers!.noLoading || showFullScreenLoading();
const token: string = globalStore.token;
return {
...config,
headers: { ...config.headers, 'x-access-token': token },
};
},
(error: AxiosError) => {
@ -63,35 +41,27 @@ class RequestHttp {
this.service.interceptors.response.use(
(response: AxiosResponse) => {
const { data, config } = response;
const globalStore = GlobalStore();
// * 在请求结束后,移除本次请求,并关闭请求 loading
axiosCanceler.removePending(config);
tryHideFullScreenLoading();
// * 登陆失效code == 599
if (data.code == ResultEnum.OVERDUE) {
ElMessage.error(data.msg);
globalStore.setToken('');
router.replace({
path: '/login',
});
return Promise.reject(data);
}
// * 全局错误信息拦截防止下载文件得时候返回数据流没有code直接报错
if (data.code && data.code !== ResultEnum.SUCCESS) {
ElMessage.error(data.msg);
return Promise.reject(data);
}
// * 成功请求(在页面上除非特殊情况,否则不用处理失败逻辑)
return data;
},
async (error: AxiosError) => {
const { response } = error;
tryHideFullScreenLoading();
// 请求超时单独判断,因为请求超时没有 response
if (error.message.indexOf('timeout') !== -1) ElMessage.error('请求超时!请您稍后重试');
// 根据响应的错误状态码,做不同的处理
if (error.message.indexOf('timeout') !== -1)
ElMessage.error(i18n.global.t('commons.msg.requestTimeout'));
if (response) checkStatus(response.status);
// 服务器结果都没有返回(可能服务器错误可能客户端断网),断网处理:可以跳转到断网页面
if (!window.navigator.onLine) router.replace({ path: '/500' });
return Promise.reject(error);
},

View file

@ -5,10 +5,10 @@ export interface Result {
}
// * 请求响应参数(包含data)
export interface ResultData {
export interface ResultData<T = any> {
code: number;
message: string;
data: any;
data: T;
}
// * 分页响应参数
@ -40,11 +40,6 @@ export namespace Login {
authMethod: string;
}
export interface ResLogin {
code: number;
data: logInfo;
message: string;
}
export interface logInfo {
name: string;
token: string;
}

View file

@ -2,9 +2,9 @@ import { Login } from '@/api/interface/index';
import http from '@/api';
export const loginApi = (params: Login.ReqLoginForm) => {
return http.post(`/auth/login`, params);
return http.post<Login.ResLogin>(`/auth/login`, params);
};
export const getCaptcha = () => {
return http.get(`/auth/captcha`);
return http.get<Login.ResCaptcha>(`/auth/captcha`);
};

View file

@ -20,6 +20,7 @@ export default {
title: 'Delete',
deleteSuccess: 'Delete Success',
loginSuccss: 'Login Success',
requestTimeout: 'The request timed out, please try again later',
},
login: {
captchaHelper: 'Please enter the verification code',

View file

@ -20,6 +20,7 @@ export default {
title: '删除',
deleteSuccess: '删除成功',
loginSuccss: '登陆成功',
requestTimeout: '请求超时,请稍后重试',
},
login: {
captchaHelper: '请输入验证码',