往期文档
9、项目引入axios,配置响应拦截和请求拦截
1)、安装axios
#npm
npm install axios
#yarn
yarn add axios
2)、录在src\config\axios 文件夹下进行axios配置
①axios通用化配置
新建type.ts文件,定义使用到的对象
import type { AxiosRequestConfig } from "axios";
import { AxiosTransform } from "./axiosTransform";
export interface RequestOptions {
// 请求参数拼接到url
joinParamsToUrl?: boolean;
// 格式化请求参数时间
formatDate?: boolean;
// 是否处理请求结果
isTransformRequestResult?: boolean;
// 是否加入url
joinPrefix?: boolean;
// 接口地址, 不填则使用默认apiUrl
apiUrl?: string;
// 错误消息提示类型
errorMessageMode?: "none" | "modal";
}
export interface CreateAxiosOptions extends AxiosRequestConfig {
prefixUrl?: string;
transform?: AxiosTransform;
requestOptions?: RequestOptions;
}
export interface Result<T = any> {
msg: string | null | undefined;
code: number;
data: T;
requestId: string;
state: number;
success: boolean;
timestamp: string;
}
新建checkStatus.ts文件,输出对应的请求错误信息
import { message } from "ant-design-vue";
export function checkStatus(status: number, msg: string): void {
switch (status) {
case 400:
message.error(`${msg}`);
break;
case 401:
message.error("用户没有权限(令牌、用户名、密码错误)!");
break;
case 403:
message.error("用户得到授权,但是访问是被禁止的。!");
break;
// 404请求不存在
case 404:
message.error("网络请求错误,未找到该资源!");
break;
case 405:
message.error("网络请求错误,请求方法未允许!");
break;
case 408:
message.error("网络请求超时!");
break;
case 500:
message.error("服务器错误,请联系管理员!");
break;
case 501:
message.error("网络未实现!");
break;
case 502:
message.error("网络错误!");
break;
case 503:
message.error("服务不可用,服务器暂时过载或维护!");
break;
case 504:
message.error("网络超时!");
break;
case 505:
message.error("http版本不支持该请求!");
break;
default:
}
}
新建数据处理axiostransform.ts 文件实现数据处理类,可以根据项目自行配置
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import type { RequestOptions, Result } from "./types";
export abstract class AxiosTransform {
/**
* @description: 请求之前处理配置
* @description: Process configuration before request
*/
beforeRequestHook?: (
config: AxiosRequestConfig,
options: RequestOptions
) => AxiosRequestConfig;
/**
* @description: 请求成功处理
*/
transformRequestData?: (
res: AxiosResponse<Result>,
options: RequestOptions
) => any;
/**
* @description: 请求失败处理
*/
requestCatch?: (e: Error) => Promise<any>;
/**
* @description: 请求之前的拦截器
*/
requestInterceptors?: (config: AxiosRequestConfig) => AxiosRequestConfig;
/**
* @description: 请求之后的拦截器
*/
responseInterceptors?: (res: AxiosResponse<any>) => AxiosResponse<any>;
/**
* @description: 请求之前的拦截器错误处理
*/
requestInterceptorsCatch?: (error: Error) => void;
/**
* @description: 请求之后的拦截器错误处理
*/
responseInterceptorsCatch?: (error: Error) => void;
}
②配置请求拦截,代码如下
// 请求之前处理config
const token = getToken();
config.headers["X-Requested-With"] = "XMLHttpRequest";
if (token) {
// jwt token
config.headers.Authorization = `Bearer ${getToken() || null}`;
}
return config;
③配置响应拦截,具体代码如下:
const { response, code, msg } = error || {};
const msg: string =
response && response.data && response.data.error
? response.data.error.message
: "";
const err: string = error.toString();
try {
if (code === "ECONNABORTED" && msg.indexOf("timeout") !== -1) {
message.error("接口请求超时,请刷新页面重试!");
return;
}
if (err && err.includes("Network Error")) {
Modal.error({
title: "网络异常",
content: "请检查您的网络连接是否正常!",
});
return;
}
} catch (e) {
throw new Error(e);
}
checkStatus(error.response && error.response.status, msg);
return error;
10、项目中引入mockjs
1)安装插件
#npm
npm install vite-plugin-mock -D
npm install mockjs -S
#yarn
yarn add vite-plugin-mock mockjs
2).在vite.config.ts中进行插件配置
import vueMockServe from 'vite-plugin-mock'
plugin:[vueMockServe({ supportTs: false })]
3)安装cross-env
#npm
npm install cross-env -S
#yarn
yarn add cross-env
4)修改项目启动脚本
"dev": "cross-env NODE_ENV=development vite",
11、安装并配置perttier
1)安装插件
#npm
npm install prettier
#yarn
yarn add prettier
2)新增配置文件prettier.config.js和.prettierignore,可自行定义
// prettier.config.js
module.exports = {
printWidth: 100,
tabWidth: 2,
useTabs: false,
semi: true,
vueIndentScriptAndStyle: true,
singleQuote: true,
alwaysParens: "avoid",
quoteProps: "as-needed",
bracketSpacing: true,
trailingComma: "none",
jsxBracketSameLine: false,
jsxSingleQuote: false,
arrowParens: "always",
insertPragma: true,
requirePragma: true,
proseWrap: "never",
htmlWhitespaceSensitivity: "strict",
endOfLine: "lf",
rangeStart: 2,
parser: "vue",
overrides: [
{
files: "*.md",
options: {
tabWidth: 2,
},
},
],
};
# .prettierignore
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*