封装axios
基本
我们每个项目基本上都会使用axios发送请求,下面是封装的一个axios
// 封装AXIOS
import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus"; // 弹框组件
// 设置基础地址
// axios.defaults.baseURL = "https://www.congmiqq.com";
axios.defaults.baseURL = import.meta.env.VITE_API_URL;
// 设置超时时间
axios.defaults.timeout = 10000;
// 接口白名单 不需要认证的接口
let whitelist = ["/aw/login", "/api/AdmAccount/GetVerificationCode", "/api/AdmAccount/Login"];
// 设置用户参数
// let token = ""
// http request 请求拦截器,有token值则配置上token值
axios.interceptors.request.use(
config => {
if (!whitelist.includes(config.url)) {
// 获取本地的存储
let token = localStorage.getItem("auth");
if (token) {
// 添加header
config.headers.auth = token;
} else {
ElMessage({
type: "error",
message: "token 过期,请重新登录",
showClose: true,
grouping: true,
onClose: () => {
// 跳转到登录页面
router.push("/login");
},
});
}
}
return config;
},
err =>
// 对于请求错误做什么
Promise.reject(err),
);
// http response 服务器响应拦截器,在接收响应做些什么,例如跳转到登录页
axios.interceptors.response.use(
// 响应成功
response => {
// console.log("响应拦截器response", response)
// response.data,
if (response.data?.code === 200) {
return response.data.data;
} else {
ElMessage({
type: "error",
message: response.data.msg,
showClose: true,
grouping: true,
});
return response.data;
}
},
// 失败的时候
error =>
// if (error.response) {
// switch (error.response.status) {
// case 404:
// alert("网络请求不存在");
// default:
// alert("网络连接出错");
// }
// }
Promise.reject(error.response?.data),
);
// 封装get和post请求
/**
* get方法,对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function get(url, params, headers = {}) {
return new Promise((resolve, reject) => {
// url是地址,params是传输的数据 header是请求头
axios
.get(url, {
params,
headers,
})
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
export const post = (url, data, headers = {}) =>
new Promise((resolve, reject) => {
let header = { headers };
axios
.post(url, data, header)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
export default { get };
统一管理接口
export const GetVerificationCode = data =>
get("/api/url", data, { aaa: "13213" });
这样我们可以在一个文件中管理接口,并且可以传递请求头
使用
const determine = async data =>{
let code = await GetVerificationCode({ loginName: data.strUser });
}
得到的code就是返回的数据
添加取消请求
使用CancelToken的方式取消请求
修改get和post请求,除了使用其他代码不变
// 封装AXIOS
import axios from "axios";
// import { CancelToken } from "axios";
import router from "@/router";
import { ElMessage } from "element-plus"; // 弹框组件
// 设置基础地址
// axios.defaults.baseURL = "https://www.congmiqq.com";
axios.defaults.baseURL = import.meta.env.VITE_API_URL;
// 设置超时时间
axios.defaults.timeout = 10000;
// 接口白名单 不需要认证的接口
let whitelist = ["/aw/login", "/api/AdmAccount/GetVerificationCode", "/api/AdmAccount/Login"];
// 设置用户参数
// let token = ""
// http request 请求拦截器,有token值则配置上token值
axios.interceptors.request.use(
config => {
if (!whitelist.includes(config.url)) {
// 获取本地的存储
let token = localStorage.getItem("auth");
if (token) {
// 添加header
config.headers.auth = token;
} else {
ElMessage({
type: "error",
message: "token 过期,请重新登录",
showClose: true,
grouping: true,
onClose: () => {
// 跳转到登录页面
router.push("/login");
},
});
}
}
return config;
},
err =>
// 对于请求错误做什么
Promise.reject(err),
);
// http response 服务器响应拦截器,在接收响应做些什么,例如跳转到登录页
axios.interceptors.response.use(
// 响应成功
response => {
// console.log("响应拦截器response", response)
// response.data,
if (response.data?.code === 200) {
return response.data.data;
} else {
ElMessage({
type: "error",
message: response.data.msg,
showClose: true,
grouping: true,
});
return response.data;
}
},
// 失败的时候
error =>
// if (error.response) {
// switch (error.response.status) {
// case 404:
// alert("网络请求不存在");
// default:
// alert("网络连接出错");
// }
// }
Promise.reject(error.response?.data),
);
// 封装get和post请求
/**
* get方法,对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function get(url, params, headers = {}) {
// 创建一个取消令牌
const source = axios.CancelToken.source();
// 发送请求
const promise = axios
.get(url, {
params,
headers,
cancelToken: source.token, // 将取消令牌添加到请求配置中
})
.then(res => res)
.catch(err => {
if (axios.isCancel(err)) {
console.log("请求已取消:", err);
throw err; // 重新抛出错误,以便调用者可以捕获
} else {
throw err;
}
});
// 返回一个对象,包含请求的 promise 和取消请求的方法
return {
promise,
cancel: () => source.cancel("Request cancelled"),
};
}
export function post(url, data, headers = {}) {
// 创建一个取消令牌
const source = axios.CancelToken.source();
// 发送请求
const promise = axios
.post(url, data, {
headers,
cancelToken: source.token, // 将取消令牌添加到请求配置中
})
.then(res => res)
.catch(err => {
if (axios.isCancel(err)) {
console.log("请求已取消:", err);
throw err; // 重新抛出错误,以便调用者可以捕获
} else {
throw err;
}
});
// 返回一个对象,包含请求的 promise 和取消请求的方法
return {
promise,
cancel: () => source.cancel("Request cancelled"),
};
}
export default { get, post };
使用
const determine = async data => {
request.value = GetVerificationCode({ loginName: data.strUser });
console.log("返回的promise和cancel", request.value);
let code = await request.value.promise;
console.log("获取验证码", code);
}
得到的code是接口返回的数据
在需要取消请求的时候执行如下就可以了
request.value.cancel();