mirror of
https://github.com/soybeanjs/soybean-admin.git
synced 2025-12-25 14:20:21 +08:00
build(deps): 添加smooth-scroll插件、axios封装
This commit is contained in:
77
src/service/request/instance.ts
Normal file
77
src/service/request/instance.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import axios from 'axios';
|
||||
import qs from 'qs';
|
||||
import { getStorageToken } from '@/utils';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import type { AxiosRequestConfig, AxiosInstance } from 'axios';
|
||||
import { errorHandler } from './errorHandler';
|
||||
|
||||
export interface StatusConfig {
|
||||
/** 表明请求状态的属性key */
|
||||
statusKey: string;
|
||||
/** 请求信息的属性key */
|
||||
msgKey: string;
|
||||
/** 成功状态的状态码 */
|
||||
successCode: string | number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 封装axios请求类
|
||||
* @author Soybean(曹理斌) 2021-03-13
|
||||
* @class CustomAxiosInstance
|
||||
*/
|
||||
export default class CustomAxiosInstance {
|
||||
instance: AxiosInstance;
|
||||
|
||||
constructor(
|
||||
axiosConfig: AxiosRequestConfig,
|
||||
statusConfig: StatusConfig = {
|
||||
statusKey: 'code',
|
||||
msgKey: 'message',
|
||||
successCode: 200
|
||||
}
|
||||
) {
|
||||
this.instance = axios.create(axiosConfig);
|
||||
this.setInterceptor(statusConfig);
|
||||
}
|
||||
|
||||
/** 设置请求拦截器 */
|
||||
setInterceptor(statusConfig: StatusConfig) {
|
||||
this.instance.interceptors.request.use(
|
||||
config => {
|
||||
const handleConfig = { ...config };
|
||||
// content-type为application/x-www-form-urlencoded类型的data参数需要序列化
|
||||
if (handleConfig.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
|
||||
handleConfig.data = qs.stringify(handleConfig.data);
|
||||
}
|
||||
// 设置token
|
||||
handleConfig.headers.Authorization = getStorageToken();
|
||||
|
||||
return handleConfig;
|
||||
},
|
||||
error => {
|
||||
errorHandler(error);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
this.instance.interceptors.response.use(
|
||||
response => {
|
||||
const { status, data } = response;
|
||||
const { statusKey, msgKey, successCode } = statusConfig;
|
||||
if (status === 200 || status < 300 || status === 304) {
|
||||
if (data[statusKey] === successCode) {
|
||||
return Promise.resolve(data.data);
|
||||
}
|
||||
ElMessage.error(data[msgKey]);
|
||||
return Promise.reject(data[msgKey]);
|
||||
}
|
||||
const error = { response };
|
||||
errorHandler(error);
|
||||
return Promise.reject(error);
|
||||
},
|
||||
error => {
|
||||
errorHandler(error);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user