axios自己使用的

import {
  getSStore,
  removeSStore,
  format
} from "@/common/utils/utils";
import * as env from "@/common/utils/env";

let v = new Vue();

// 获取url中指定的参数
const getUrlParam = (name) => {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg); //匹配目标参数
  if (r != null) return unescape(r[2]);
  return null; //返回参数值
};

//创建一个axios请求
const serviceHttp = axios.create({
  baseURL: getUrlParam("host") || env.baseUrl,
  timeout: 50000,
  emulateJSON: true,
  headers: {
    // 'X-Requested-With': 'XMLHttpRequest',
    // 'Content-Type': 'application/json'
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  },
});

// 请求时的拦截
serviceHttp.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应时拦截
serviceHttp.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    return Promise.resolve(error.response);
  }
);

//链式处理第一步,判断http状态码是否正常,和拦截器一样,请求正常则返回响应,请求异常则返回错误,最后返回结果给checkCode()。
const checkStatus = (response) => {
  if (!response) {
    v.$message({
      type: "error",
      message: "网络请求失败",
    });
  }
  if (response && response.status === 404) {
    v.$message({
      type: "error",
      message: "服务器找不到请求的页面",
    });
  } else if (response && response.status === 500) {
    v.$message({
      type: "error",
      message: "服务器内部错误",
    });
  }

  if (
    response &&
    (response.status === 200 ||
      response.status === 304 ||
      response.status === 400)
  ) {
    return response;
    // 如果不需要除了data之外的数据,可以直接 return response.data
  }
  return response;
};

//链式处理第二步,处理上一步的结果,分别处理网络异常,以及后端返回的异常。
const checkCode = (url, res) => {
  if (!res) {
    return res;
  }
  let data = res.data;
  let code = data.code;
  if (code === 0) {
    return data;
  } else if (code === 2000) {
    v.$confirm("登录已失效,请重新登录", "提示", {
      confirmButtonText: "确定",
      showCancelButton: false,
      type: "warning",
    }).then(function () {
      removeSStore("token");
      // window.open('http://localhost:8086/#/');
      window.close();
    });
  } else {
    v.$message({
      type: "error",
      message: data.msg,
    });
  }
  return res;
};

const http = {
  post: (url, params, baseURL, conntentType) => {
    if (conntentType == "application/json") {
      serviceHttp.defaults.headers["Content-Type"] =
        "application/json;charset=UTF-8";
    } else {
      serviceHttp.defaults.headers["Content-Type"] =
        "application/x-www-form-urlencoded;charset=UTF-8";
    }
    let urlArr = ["/userLogin"];
    if (!urlArr.includes(url) && getSStore("token")) {
      serviceHttp.defaults.headers["Login-Token"] = getSStore("token") || "";
    }
    const requestParam = {
      method: "post",
      url: url,
      data: conntentType == "application/json" ?
        JSON.stringify(params) : Qs.stringify(params),
    };
    baseURL && (requestParam.baseURL = baseURL);
    return new Promise((resolve, reject) => {
      serviceHttp(requestParam)
        .then((response) => {
          const resp = checkStatus(response);
          if (resp === undefined) {
            resolve(resp);
          } else {
            return resp;
          }
        })
        .then((res) => {
          resolve(checkCode(url, res));
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  postpl: (url, params) => {
    return http.post(url, params, "application/json");
  },

  get: (url, params, conntentType) => {
    if (conntentType == "application/json") {
      serviceHttp.defaults.headers["Content-Type"] =
        "application/json;charset=UTF-8";
    } else {
      serviceHttp.defaults.headers["Content-Type"] =
        "application/x-www-form-urlencoded;charset=UTF-8";
    }
    params["sysToken"] = getSStore("token");
    return new Promise((resolve, reject) => {
      serviceHttp({
          method: "get",
          url: url,
          params: params,
          paramsSerializer: function (params) {
            return Qs.stringify(params, {
              arrayFormat: "brackets",
            });
          },
        })
        .then((response) => {
          return checkStatus(response);
        })
        .then((res) => {
          resolve(checkCode(url, res));
        })
        .catch(() => {
          reject();
        });
    });
  },
  
  exportExcel: (url, params, name, baseURL, conntentType) => {
    if (conntentType == "application/json") {
      serviceHttp.defaults.headers["Content-Type"] =
        "application/json;charset=UTF-8";
    } else {
      serviceHttp.defaults.headers["Content-Type"] =
        "application/x-www-form-urlencoded;charset=UTF-8";
    }
    let urlArr = ["/userLogin"];
    if (!urlArr.includes(url) && getSStore("token")) {
      serviceHttp.defaults.headers["Login-Token"] = getSStore("token") || "";
    }
    const requestParam = {
      method: "post",
      url: url,
      data: conntentType == "application/json" ?
        JSON.stringify(params) : Qs.stringify(params),
      responseType: "arraybuffer"
      // withCredentials: true
    };
    baseURL && (requestParam.baseURL = baseURL);

    return new Promise((resolve, reject) => {
      serviceHttp(requestParam)
        .then((response) => {
          let blob = new Blob([response.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          });
          var time = new Date();
          var ymd = format("YYYYMMDD", time);
          var filename = name + ymd + time.getHours() + time.getMinutes() + time.getSeconds() + ".xlsx";
    
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, filename);
            resolve()
          } else {
            var objectUrl = window.URL.createObjectURL(blob);
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.setAttribute("style", "display:none")
            a.setAttribute("href", objectUrl)
            a.setAttribute("download", filename)
            a.click();
            URL.revokeObjectURL(objectUrl);
            resolve()
          }
        })
        .catch((err) => {
          reject(err);
        });
    });

    // axios.post(url, params, {
    //   responseType: "arraybuffer"
    //   // withCredentials: true
    // }).then(response => {
    //   let blob = new Blob([response.data], {
    //     type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    //   });
    //   var time = new Date();
    //   var ymd = format("YYYYMMDD", time);
    //   var filename = name + ymd + time.getHours() + time.getMinutes() + time.getSeconds() + ".xlsx";

    //   if (window.navigator.msSaveOrOpenBlob) {
    //     navigator.msSaveBlob(blob, filename);
    //   } else {
    //     var objectUrl = window.URL.createObjectURL(blob);
    //     var a = document.createElement("a");
    //     document.body.appendChild(a);
    //     a.setAttribute("style", "display:none")
    //     a.setAttribute("href", objectUrl)
    //     a.setAttribute("download", filename)
    //     a.click();
    //     URL.revokeObjectURL(objectUrl);
    //   }
    // })
  }

};

export default http;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值