Axios配置 基础的get post
安装axios...
在src/utils/axios.js(新建一个)
/** * axios 配置 转载于(https: //segmentfault.com/a/1190000016680014) * (https://segmentfault.com/a/1190000013507743?utm_source=sf-similar-article) * @author lpy * @date 2021/08/06 */ import axios from "axios"; import qs from "qs"; // 判定开发模式 // if (process.env.NODE_ENV === "development") { // axios.defaults.baseURL = "/api"; // } else if (process.env.NODE_ENV === "production") { axios.defaults.baseURL = "http://www.baidu.com/"; // } // 设置全局头信息 axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8"; // 全局设置超时时间 axios.defaults.timeout = 10000; const axiosInstance = axios.create({ // baseURL:"/sqlData", timeout:10000, headers:{ "Content-Type": "application/json;charset=UTF-8" } }) export default axiosInstance; export function get(url, params) { return new Promise((resolve, reject) => { axios.get(url, { params: params }).then(res => { resolve(res.data); }).catch(err => { reject(err.data) }) }); }; export function post(url, params) { return new Promise((resolve, reject) => { axios({ method: "post", url: url, data: params, headers: { "Content-Type": "application/json", }, transformRequest(data, headers) { return JSON.stringify(data); }, }) .then((res) => { // console.log("请求结果:", res.data.data.items); resolve(res.data.data.items) }) .catch((err) => { reject("错误信息:", err); }); }) } /** * 下载文件 * @param {*} url: 请求地址 * @param {*} params: 请求参数 */ export function downFile(url, params) { return new Promise((resolve, reject) => { axios({ method: "get", url: url, params: params, headers: { "Content-Type":"application/x-www-form-urlencoded" }, responseType: 'blob', }) .then((res) => { resolve(res) }) .catch((err) => { reject("错误信息:", err); }); }) }
在Main.js中挂
使用举例
exportExcel() { let fileName = "checkInTable.xlsx"; if (this.selectMonth) { let month = this.$moment(this.selectMonth).format("YYYY-MM"); console.log("month", month); this.downFile("/monthExportChecin", { yearMonth: month, }) .then((res) => { this.download(res.data, fileName); }) .catch((req) => { console.log("下载失败", req); }); } else { let min = this.minDate; let max = this.maxDate; console.log('min max',min,max) this.downFile("/exportChecin", { endDate: "2021-07-10", startDate: "2021-07-09" }) .then((res) => { this.download(res.data, fileName); }) .catch((req) => { console.log("下载失败", req); }); } }, // 下载文件 download(data, fileName) { if (!data) { return; } let url = window.URL.createObjectURL(new Blob([data])); let link = document.createElement("a"); link.style.display = "none"; link.href = url; link.setAttribute("download", fileName); document.body.appendChild(link); link.click(); },
人生到处知何似,应似飞鸿踏雪泥。