1. 如果对axios不了解的可以先移步中文axios网
axios中文文档|axios中文网 | axioshttp://www.axios-js.com/zh-cn/docs/2. 这是稀土掘金上的关于axios的封装个人感觉比较细节易懂
vue中Axios的封装和API接口的管理 - 掘金回归正题,我们所要的说的axios的封装和api接口的统一管理,其实主要目的就是在帮助我们简化代码和利于后期的更新维护。 在vue项目中,和后台交互获取数据这块,我们通常使用的是axios库,它是基于promise的http库,可运行在浏览器端和node.js中。他有很多优秀的…https://juejin.cn/post/6844903652881072141==========================华丽分割线=================================
以下是我在实际开发中的使用:
1. 文件目录 base.ts 是axios封装的核心文件
2, requestOptions文件(import { ContentType } from "./requestOptions")
export const enum ContentType {
json = "application/json;charset=UTF-8",
form = "application/x-www-form-urlencoded; charset=UTF-8",
download = "application/octet-stream",
upload = "multipart/form-data"
}
3.getRequestErrorMsg(import { getRequestErrorMsg } from "@/pc/utils")
/**
* 获取网络错误
* @param e
* @param defaultRet
*/
export function getRequestErrorMsg(e, defaultRet = "网络开小差,请稍后再试") {
return e && e.data && e.data.data ? e.data.data : defaultRet;
}
3. base.ts文件内容
/* eslint-disable */
import EventBus from "@/pc/eventBus";
import { Message } from "element-ui";
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { ContentType } from "./requestOptions";
import _ from "lodash";
import qs from "qs";
import { getRequestErrorMsg } from "@/pc/utils";
const TIME_OUI = 300 * 1000; // 超时
const TOKEN = "TOKEN"; // token键值
const baseURL = "/api"; // api前缀
const baseOptions: AxiosRequestConfig = {
baseURL: baseURL,
timeout: TIME_OUI,
withCredentials: true, // 不论是否跨域,都发送cookies
headers: {
"Content-Type": ContentType.json
}
};
const service = axios.create(baseOptions);
// 请求拦截
service.interceptors.request.use(
config => {
// 如果有token,加上token
const token = sessionStorage.getItem(TOKEN);
if (token) {
config.headers.token = token;
}
return config;
},
error => {
console.error("request error", error);
Promise.reject(error);
}
);
let loginMessage = false;
// 返回拦截
service.interceptors.response.use(
async res => {
// response interceptors cookies拦截器,存入token
if (res.headers["set-token"]) {
const token = res.headers["set-token"];
sessionStorage.setItem(TOKEN, token);
}
// const responseType: string = res.config.responseType as string;
// if (responseType === "blob") {
// return res;
// }
// return res.data;
return res;
}, (error) => {
return Promise.reject(error ? error.response : "未知错误");
}
);
const ErrorTimeOut = 10 * 1000;
const baseRequest = (requestOptions, notifyIfError = false, messageOpt = {}) => {
return new Promise((resolve, reject) => {
service(requestOptions)
.then((res: AxiosResponse<{ code: number; message: string; data: any }>) => {
const responseType: string = res.config.responseType as string;
if (responseType === "blob") {
resolve(res.data);
}
// 统一处理业务级别的错误字段 code
else if (res.data && res.data.code && res.data.code != 200) {
res.data.message && EventBus.$emit("errorNotify", res.data.message || "未知错误,请稍后重试");
reject(res.data);
} else {
resolve(res.data.data);
}
})
.catch(e => {
const status = e && e.status;
let errorMsg = "请求失败,请稍后重试";
if (e && e.data && e.data.data) {
errorMsg = e.data.data;
}
// 处理导出时blob错误信息(1层)
if (e && e.config && e.config.responseType === "blob") {
let reader = new FileReader();
reader.readAsText(e.data, "utf-8");
reader.onload = function() {
Message({
message: JSON.parse(this.result as string)?.data || "未知错误",
type: "error",
duration: ErrorTimeOut,
...messageOpt
});
};
return reject(e);
}
switch (+status) {
case 401:
if (!loginMessage) {
Message({
message: "登录已超时,请重新登录!",
center: true,
type: "warning",
onClose() {
loginMessage = false;
}
});
loginMessage = true;
}
EventBus.$emit("goLogin");
return reject(e);
case 417:
Message({
message: errorMsg,
type: "error",
duration: ErrorTimeOut,
...messageOpt
});
return reject(e);
case 412:
EventBus.$emit("removeToken", undefined);
Message({
message: e.data.data,
type: "error",
duration: ErrorTimeOut
});
return reject(e);
case 500:
Message({
message: errorMsg,
type: "error",
duration: ErrorTimeOut
});
return reject(e);
}
if (notifyIfError) {
const msg = getRequestErrorMsg(e);
EventBus.$emit("errorNotify", msg);
}
return reject(e);
});
});
};
/**
* get 请求
* @param url
* @param params
* @param notifyIfError
* @return Promise
*/
export const fetchGet = (url, params, options = {}, notifyIfError = false) => {
return baseRequest(
{
url,
method: "get",
params,
...options
},
notifyIfError
);
};
/**
* post 请求
* @param url
* @param data
* @param params
* @param options axios 其他配置项
* @oaram notifyIfError 是否发送系统级错误提示
* @param messageOpt message提示配置项
* @return Promise
*/
export const fetchPost = (url, data = {}, params = {}, options = {}, notifyIfError = false, messageOpt = {}) => {
return baseRequest(
{
url,
method: "post",
params,
data,
...options
},
notifyIfError,
messageOpt
);
};
/**
* patch 请求
* @param url
* @param data
* @param params
* @return Promise
*/
export const fetchPatch = (url, data = {}, params = {}, notifyIfError = false) => {
return baseRequest(
{
url,
method: "patch",
params,
data
},
notifyIfError
);
};
/**
* put 请求
* @param url
* @param data
* @param params
* @return Promise
*/
export const fetchPut = (url, data = {}, params = {}, notifyIfError = false) => {
return baseRequest(
{
url,
method: "put",
params,
data
},
notifyIfError
);
};
/**
* delete 请求
* @param url
* @param data
* @param params
* @return Promise
*/
export const fetchDel = (url, data = {}, params = {}, notifyIfError = false) => {
return baseRequest(
{
url,
method: "delete",
params,
data
},
notifyIfError
);
};
/**
* download 请求
* @param url
* @param data
* @param params
* @return Promise
*/
export const fetchDownload = (url, data = {}, params = {}, notifyIfError = false) => {
return baseRequest(
{
url,
method: "post",
headers: {
"Content-Type": ContentType.download,
responseType: "blob"
},
params,
data,
responseType: "blob"
},
notifyIfError
);
};
export const fetchUpload = (url, data = {}, params = {}, options = {}) => {
return baseRequest({
url,
method: 'post',
headers: {
"Content-Type": ContentType.upload
},
params,
data,
...options
});
}
export default service;
4. 分模块使用
import { fetchGet, fetchPost } from "../../request";
export default {
//列表
getIns(data?: Record<string, any>) {
return fetchPost("/ambondtrade/getIns", data);
},
getProductGroup(params) {
return fetchGet("/trade/getProductGroup", params);
},
}
5. 该模块导出
import DealInquery from "./DealInquery";
import PmIntentInstruction from "./PmIntentInstruction";
export default {
...DealInquery,
...PmIntentInstruction
};
6. 所有模块api导出
7. main.ts中引入
8. api的使用
this.$api.BondTrade.stopPMInstruction({ insNo: row.insNo }).then(res => {
this.$message.success(res);
this.getData(this.aboutBondInfo);
});
9. 下载方法使用(fetchDownload)
// js文件(用于联调后端的接口)
import { fetchGet, fetchPost, fetchDownload, fetchDel } from "./request";
export function getExceltemp() {
return fetchDownload("/srpSurvey/brokerAppointment/downloadExcelTemplate");
}
10. 使用
const data = await getExceltemp();
downLoadExcel(data, "上传预约模板");
11. downLoadExcel方法(util.ts)
/*文件下载方法*/
export function downLoadExcel(data: Blob, fileName: string) {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", `${fileName}.xlsx`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
export function downLoadzip(data: Blob, fileName: string) {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", `${fileName}.zip`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
export function downloadFile(data: Blob, fileName: string) {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", `${fileName}`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
export function downloadZip(data: Blob, fileName: string) {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", `${fileName}.zip`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
export function downLoadDocument(data: Blob, fileName: string, suffixName: string) {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", `${fileName}.${suffixName}`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
12. 上传方的使用
//导入
importCompanyIndicatorVal(params) {
return fetchUpload("/creditScorecard/importCompanyIndicatorVal", params);
}
async handleUpload(file) {
if (!file) return;
const formData = new FormData();
formData.append("file", file.raw);
formData.append("industry", this.industry);
this.buttonLoading = 2;
try {
await this.$api.CreditScore.importCompanyIndicatorVal(formData);
this.$message.success("导入成功");
this.$emit("fresh");
} finally {
this.buttonLoading = 0;
}
}
13. 以上为使用全过程。