封装 axios:
import axios from "axios";
const server = axios.create({
timeout: 20000,
withCredentials: true,
headers: {"Content-Type": "application/json; charset=utf-8"},
});
// 申请拦截器
server.interceptors.request.use(function (config) {
// 在发送申请之前做些什么
let userinfo = JSON.parse(window.localStorage.getItem("userinfo"));
if (userinfo) {config.headers.Authorization = userinfo.token;}
return config;
},
function (error) {
// 对申请谬误做些什么
return Promise.reject(error);
}
);
// 响应拦挡
server.interceptors.response.use(function (response) {
// 如果返回的状态码为 200,阐明接口申请胜利,能够失常拿到数据否则的话抛出谬误
if (response.status === 200) {
// 未登录或者 token 过期
if (response.data.err === 1) {localStorage.removeItem("userinfo");
setTimeout(() => {router.push("/login");
}, 1000);
} else if (response.data.err === 10) {setTimeout(() => {router.push("/nopower");
}, 1000);
}
return Promise.resolve(response);
} else {return Promise.reject(response);
}
},
function (error) {if (error.response.status) {switch (error.response.status) {
case 401:
break;
case 404:
Message.error("网络申请不存在");
break;
// 其余谬误,间接抛出谬误提醒
case 500:
if (error.response.data.err === 1) {localStorage.removeItem("userinfo");
setTimeout(() => {router.push("/login");
}, 1000);
}
break;
default:
Message.error(error.response.data.msg);
}
return Promise.reject(error.response.data.msg);
}
}
);
server.adornUrl = (actionName) => {// 非生产环境 && 开启代理, 接口前缀对立应用 [/proxyApi/] 前缀做代理拦挡!
return "/api" + actionName;
};
export default server;
申请接口:
import server from "@/api/request";
export const exportLogin = async (data) => await server.post("/farm/sys/log/exportLogin", data, { responseType: "blob"})
次要代码:
exportLogin({
pn: this.currentPage,
ps: this.pageSize,
}).then((res) => {
this.exportLoading = false;
const fileName = ` 名字 ${+new Date()}.xlsx`;
const blob = new Blob([res.data], {type: "application/vnd.ms-excel;charset=utf-8",});
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
URL.revokeObjectURL(link.href);
})
.catch((err) => {this.$message.error({ message: err});
this.exportLoading = false;
});