axios 请求拦截、续订token、显示loading、禁止键盘

import cacheHelper from '../helper/cacheHelper';
import axios from "axios";
import env from "../http/env";
import { Loading } from 'element-ui';
import { WindowsToaster } from "node-notifier";
import Linq from "linq";
import $ from 'jquery'

let loading;
var globalRequestId = 0;
var requestList = new Array();
var loadingShowing = false;
const service = axios.create({
  baseURL: env.dev.baseUrl,
  settimeout: 3000,
});

const request = function () {
  var parameters = [];
  var exp = [];
  for (var i = 0; i < arguments.length; i++) {
    parameters.push(arguments[i]);
    exp.push("parameters[" + i + "]");
  }
  var exp = "service(" + exp.join(",") + ")";
  var promise = eval(exp);
  promise.realThen = promise.then;
  promise.requestParameters = parameters;
  promise.requestExpression = exp;
  promise.then = function (arg) {
    return new Promise(resolve => {
      promise.realThen(result => {
        if (result.code != 401) {
          promise.realThen(arg);
          return;
        }
        axios.get(env.dev.baseUrl + "/authorize/webLogin")
          .then(function (response) {
            if (response.data.code == "0") {
              console.log("auto login");
              cacheHelper.setToken(response.data.data.token);
              setTimeout(function () {
                cacheHelper.getBasicInfo(function () {
                  var parameters = promise.requestParameters;
                  var exp = promise.requestExpression;
                  eval(exp).then(arg);
                });
              }, 1);
            }
            else if (response.data.code == "2001") {
              window.location.href = '/bacs/bacs/user/gotoMainConsolePage.action'
            }
            else if (response.data.code == "2000") {
              window.alert(response.data.msg);
              window.location.href = '/bacs/bacs/user/gotoMainConsolePage.action'
            }
          });
      });
    });
  };
  return promise;
}

export default request;

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    var requestId = (++globalRequestId) % 100000000;
    var url = config['url']
    var token = cacheHelper.getToken();
    config.headers["token"] = token;
    config.headers["requestId"] = requestId;
    startLoading(requestId);
    return config;
  },
  error => {
    var requestId = response.config.headers["requestId"];
    closeLoading(requestId);
    return Promise.reject("请求出错", error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  response => {
    var requestId = response.config.headers["requestId"];
    closeLoading(requestId);
    return response.data;
  },
  error => {
    var requestId = error.config.headers["requestId"];
    closeLoading(requestId);
    console.log("返回数据出错", error);
    return Promise.reject(error);
  },
);

$(function () {
  $(document).on("keydown", function (event) {
    if(loadingShowing)
      console.log("hooked invalid keydown!");
    return !loadingShowing;
  });
});

function startLoading(id) {
  requestList.push(id);
  loading = Loading.service({
    lock: true,
    text: '加载中...',
    spinner: "el-icon-loading",
    background: 'rgba(255,255,255,0.5)'
  });
  loadingShowing = true;
  setTimeout(() => {
    var requestIndex = Linq.from(requestList).indexOf(x => x == id);
    if (requestIndex >= 0)
      requestList.splice(requestIndex, 1);
    if (requestList.length <= 0) {
      loadingShowing = false;
      loading.close();
    }
  }, 15000);
}

function closeLoading(id) {
  var requestIndex = Linq.from(requestList).indexOf(x => x == id);
  if (requestIndex >= 0)
    requestList.splice(requestIndex, 1);
  if (requestList.length <= 0)
  {
    loadingShowing = false;
    loading.close();
  }
}

 

posted on 2021-11-11 18:33  空明流光  阅读(311)  评论(0编辑  收藏  举报

导航