refactor(projects): 修改了axios的请求封装

This commit is contained in:
‘chen.home’ 2022-08-07 18:46:41 +08:00
parent 07bbdc6b18
commit 6fe21adfa9
12 changed files with 276 additions and 120 deletions

@ -4,23 +4,23 @@ type ServiceEnv = Record<ServiceEnvType, ServiceEnvConfig>;
/** 不同请求服务的环境配置 */
const serviceEnv: ServiceEnv = {
dev: {
url: 'http://localhost:8080',
url: 'https://mock.mengxuegu.com/mock/61e4df7c17249f68847fc191/api',
urlPattern: '/url-pattern',
secondUrl: 'http://localhost:8081',
secondUrlPattern: '/second-url-pattern'
secondUrlPattern: '/second-url-pattern',
},
test: {
url: 'http://localhost:8080',
urlPattern: '/url-pattern',
secondUrl: 'http://localhost:8081',
secondUrlPattern: '/second-url-pattern'
secondUrlPattern: '/second-url-pattern',
},
prod: {
url: 'http://localhost:8080',
urlPattern: '/url-pattern',
secondUrl: 'http://localhost:8081',
secondUrlPattern: '/second-url-pattern'
}
secondUrlPattern: '/second-url-pattern',
},
};
/**

@ -1 +1 @@
VITE_HTTP_PROXY=Y
VITE_HTTP_PROXY=N

1
src/service/api/index.ts Normal file

@ -0,0 +1 @@
export * from './login';

25
src/service/api/login.ts Normal file

@ -0,0 +1,25 @@
import { request } from '../http';
interface Itest {
data: string;
}
/* get方法测试 */
export function fetachGet() {
return request.get('/getAPI');
}
/* post方法测试 */
export function fetachPost(params: Itest) {
return request.post('/postAPI', params);
}
/* delete方法测试 */
export function fetachDelete() {
return request.Delete('/deleteAPI');
}
/* put方法测试 */
export function fetachPut(params: Itest) {
return request.put('/putAPI', params);
}
/* patch方法测试 */
export function fetachPatch(params: Itest) {
return request.patch('/patchAPI', params);
}

10
src/service/http/index.ts Normal file

@ -0,0 +1,10 @@
import { getServiceEnvConfig } from '~/.env-config';
import { createRequest } from './request';
const { url, urlPattern, secondUrl, secondUrlPattern } = getServiceEnvConfig(import.meta.env);
const isHttpProxy = import.meta.env.VITE_HTTP_PROXY === 'Y';
export const request = createRequest({ baseURL: isHttpProxy ? urlPattern : url });
// export const secondRequest = createRequest({ baseURL: isHttpProxy ? secondUrlPattern : secondUrl });

@ -0,0 +1,105 @@
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
/**
* @description: axios请求类
*/
export default class createAxiosInstance {
// axios 实例
instance: AxiosInstance;
// 后台字段配置
backendConfig: Service.BackendResultConfig;
// 基础配置
axiosConfig: AxiosRequestConfig = {};
constructor(
axiosConfig: AxiosRequestConfig,
backendConfig: Service.BackendResultConfig = {
codeKey: 'code',
dataKey: 'data',
msgKey: 'msg',
successCode: '200',
},
) {
this.backendConfig = backendConfig;
// 设置了axios实例上的一些默认配置,新配置会覆盖默认配置
this.instance = axios.create({ timeout: 60000, ...axiosConfig });
this.setInterceptor();
}
// 设置类拦截器
setInterceptor() {
this.instance.interceptors.request.use(
(config: AxiosRequestConfig) => {
// 一般会请求拦截里面加token
// const token = localStorage.getItem('token') as string;
// config.headers!.Authorization = token;
return config;
},
(err: any) => Promise.reject(err),
);
this.instance.interceptors.response.use(
// 因为接口的数据都在res.data下所以直接返回res.data
// 系统如果有自定义code也可以在这里处理
(res: AxiosResponse) => {
// apiData 是 API 返回的数据
const apiData = res.data;
// 这个 Code 是和后端约定的业务 Code
const code = String(res.data[this.backendConfig.codeKey]);
switch (code) {
case this.backendConfig.successCode:
// code === 200 代表没有错误,直接返回约定的数据内容
return apiData[this.backendConfig.dataKey];
default:
// 不是正确的 Code,返回错误提示信息
return Promise.reject(new Error(`Error:${this.backendConfig.dataKey}`));
}
},
(err: any) => {
// 这里用来处理http常见错误进行全局提示
let message = '';
switch (err.response.status) {
case 400:
message = '请求错误(400)';
break;
case 401:
message = '未授权,请重新登录(401)';
// 这里可以做清空storage并跳转到登录页的操作
break;
case 403:
message = '拒绝访问(403)';
break;
case 404:
message = '请求出错(404)';
break;
case 408:
message = '请求超时(408)';
break;
case 500:
message = '服务器错误(500)';
break;
case 501:
message = '服务未实现(501)';
break;
case 502:
message = '网络错误(502)';
break;
case 503:
message = '服务不可用(503)';
break;
case 504:
message = '网络超时(504)';
break;
case 505:
message = 'HTTP版本不受支持(505)';
break;
default:
message = `连接出错(${err.response.status})!`;
}
// 这里是AxiosError类型所以一般我们只reject我们需要的响应即可
return Promise.reject(err.response);
},
);
}
}

@ -0,0 +1,83 @@
import type { AxiosRequestConfig } from 'axios';
import createAxiosInstance from './instance';
/**
* @description:
* @param {AxiosRequestConfig} axiosConfig - axios配置
* @param {Service} backendConfig -
* @return {*}
*/
export function createRequest(axiosConfig: AxiosRequestConfig, backendConfig?: Service.BackendResultConfig) {
const axiosInstance = new createAxiosInstance(axiosConfig, backendConfig);
const { instance } = axiosInstance;
/**
* @description:
* @param {string} url-
* @param {RequestMethod} method -
* @param {any} data -
* @param {AxiosRequestConfig} config -
* @return {*}
*/
type RequestMethod = 'get' | 'post' | 'put' | 'delete' | 'patch';
const request = async (url: string, method: RequestMethod = 'get', data: any, config?: AxiosRequestConfig) => {
return instance(url, { method, data, ...config });
};
/**
* @description: get请求
* @param {string} url -
* @return {*}
*/
const get = async (url: string, config?: AxiosRequestConfig) => {
return instance.get(url, config);
};
/**
* post请求
* @param url -
* @param data - body的data
* @param config - axios配置
*/
const post = async (url: string, data?: any, config?: AxiosRequestConfig) => {
return instance.post(url, data, config);
};
/**
* Delete请求
* @param url -
* @param config - axios配置
*/
const Delete = async (url: string, config?: AxiosRequestConfig) => {
return instance.delete(url, config);
};
/**
* put请求
* @param url -
* @param data - body的data
* @param config - axios配置
*/
const put = async (url: string, data?: any, config?: AxiosRequestConfig) => {
return instance.put(url, data, config);
};
/**
* patch请求
* @param url -
* @param data - body的data
* @param config - axios配置
*/
const patch = async (url: string, data?: any, config?: AxiosRequestConfig) => {
return instance.patch(url, data, config);
};
return {
request,
get,
post,
Delete,
put,
patch,
};
}

@ -1,54 +0,0 @@
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
/**
* @description: axios请求类
*/
export default class createAxiosInstance {
// axios 实例
instance: AxiosInstance;
// 后台字段配置
backendConfig: Service.BackendResultConfig;
// 基础配置url和超时时间
baseConfig: AxiosRequestConfig = { baseURL: '/api', timeout: 60000 };
constructor(
config: AxiosRequestConfig,
backendConfig: Service.BackendResultConfig = {
codeKey: 'code',
dataKey: 'data',
msgKey: 'msg',
successCode: '200',
},
) {
this.backendConfig = backendConfig;
this.instance = axios.create(config);
this.setInterceptor();
}
// 设置类拦截器
setInterceptor() {
this.instance.interceptors.request.use(
(config: AxiosRequestConfig) => {
// 一般会请求拦截里面加token
console.log('全局请求拦截器');
return config;
},
(err: any) => err,
);
this.instance.interceptors.response.use(
// 因为接口的数据都在res.data下所以直接返回res.data
// 系统如果有自定义code也可以在这里处理
(res: AxiosResponse) => {
console.log('全局响应拦截器');
return res.data;
},
(err: any) => {
// 这里用来处理http常见错误进行全局提示
console.log('错误状态码:', err.response.status);
// 这里是AxiosError类型所以一般我们只reject我们需要的响应即可
return Promise.reject(err.response);
},
);
}
}

@ -1,58 +0,0 @@
import type { AxiosInstance, AxiosRequestConfig } from 'axios';
import createAxiosInstance from './instance';
type RequestMethod = 'get' | 'post' | 'put' | 'delete';
// 获取aixos请求方法
async function getRequestResponse(
instance: AxiosInstance,
method: RequestMethod,
url: string,
data?: any,
config?: AxiosRequestConfig,
) {
let res: any;
if (method === 'get' || method === 'delete') {
res = await instance[method](url, config);
} else {
res = await instance[method](url, data, config);
}
return res;
}
interface RequestParam {
url: string;
method?: RequestMethod;
data?: any;
axiosConfig?: AxiosRequestConfig;
}
export function createRequest(axiosConfig: AxiosRequestConfig, backendConfig?: Service.BackendResultConfig) {
const axiosInstance = new createAxiosInstance(axiosConfig, backendConfig);
/**
* promise请求
* @param param -
* - url: 请求地址
* - method: 请求方法(get)
* - data: 请求的body的data
* - axiosConfig: axios配置
*/
async function asyncRequest(param: RequestParam) {
const { instance } = axiosInstance;
const method = param.method || 'get';
const { url } = param;
const res = await getRequestResponse(instance, method, url, param.data, param.axiosConfig);
return res;
}
/**
* @description: get请求
* @param {string} url
* @param {AxiosRequestConfig} config
* @return {*}
*/
function get(url: string, config: AxiosRequestConfig) {
return asyncRequest({ url, method: 'get', axiosConfig: config });
}
}

@ -2,7 +2,8 @@
<div text-center flex-col-center wh-full>
<h1 font="bold" text-5xl>{{ msg }}</h1>
<div m-10>
Already configured: vue3vite3unocsseslintprettiertstsxconventionalhusklint-stagedvue-router
Already configured:
vue3vite3unocsseslintprettiertstsxconventionalhusklint-stagedvue-routeraxios
</div>
<div c-lightBlue><router-link to="/">Go to layout</router-link></div>
</div>

@ -1,12 +1,55 @@
<template>
<div text-center c-blue>I prove that you have made the jump test1.</div>
<div @click="pinter">click me</div>
<div text-center cursor-pointer>
<div hover:c-blue @click="pinter">click check env</div>
<div hover:c-blue @click="get">click to get</div>
<div hover:c-blue @click="post">click to post</div>
<div hover:c-blue @click="delete2">click to delete</div>
<div hover:c-blue @click="put">click to put</div>
<div hover:c-blue @click="patch">click to patch</div>
</div>
</template>
<script setup lang="ts">
import { fetachGet, fetachPost, fetachDelete, fetachPut, fetachPatch } from '@/service/api';
const pinter = () => {
console.log('打印环境配置', import.meta.env);
};
const get = () => {
fetachGet().then((res) => {
console.log(res);
});
};
const delete2 = () => {
fetachDelete().then((res) => {
console.log(res);
});
};
const post = () => {
const params = {
data: '2022-2-2',
};
fetachPost(params).then((res) => {
console.log(res);
});
};
const put = () => {
const params = {
data: '2022-2-2',
};
fetachPut(params).then((res) => {
console.log(res);
});
};
const patch = () => {
const params = {
data: '2022-2-2',
};
fetachPatch(params).then((res) => {
console.log(res);
});
};
</script>
<style scoped></style>