在线json

https://www.json.cn/

接口错误码

  1. 其它如果错误了,可以直接弹出error.errorTextt提示
 /// <summary>
        /// 22001 无效的AccessToken
        /// </summary>
        public static Error TOKEN_22001 = new Error { ErrorCode = 22001, ErrorText = "无效的AccessToken" };
        /// <summary>
        /// 22002 过期的AccessToken  执行刷新接口
        /// </summary>
        public static Error TOKEN_22002 = new Error { ErrorCode = 22002, ErrorText = "过期的AccessToken" };
        /// <summary>
        /// 22003 无效的Grant Scope
        /// </summary>
        public static Error TOKEN_22003 = new Error { ErrorCode = 22003, ErrorText = "无效的Grant Scope" };
        /// <summary>
        /// 22004 无效的Grant Type
        /// </summary>
        public static Error TOKEN_22004 = new Error { ErrorCode = 22004, ErrorText = "无效的Grant Type" };


        /// <summary>
        /// TOKEN_22005 无效的RefreshToken
        /// </summary>
        public static Error TOKEN_22005 = new Error { ErrorCode = 22005, ErrorText = "无效的RefreshToken" };
        /// <summary>
        ///无效的Authorization
        /// </summary>
        public static Error TOKEN_22006 = new Error { ErrorCode = 22006, ErrorText = "无效的Authorization" };

        /// <summary>
        /// 无效的authorization,必须包含【{0} 】
        /// </summary>
        public static Error TOKEN_22007 = new Error { ErrorCode = 22007, ErrorText = "无效的authorization,必须包含【{0} 】" };

axios统一拦截处理 req-axios.js

  1. 代码里面对应的window.$appConfig.api.root等缓存业务代码

import {
    $headers
} from "./req-headers";
// 创建axios实例
const instance = axios.create({
    baseURL: window.$appConfig.api.root, // api的base_url
    timeout: 100000 // 请求超时时间
});

// request拦截器
instance.interceptors.request.use(
    config => {
        //设置头部信息
        config.headers = $headers(config.headers);
        return config;
    },
    error => {
        store.dispatch("dataLoading", false);
        // MsgBox.error("请求超时");
        Promise.resolve(error);
    }
);


function refreshToken(params) {
    return instance({
        url: $configAuth.auth.refresh.url,
        method: "get",
        params: params
    });
}


// 是否正在刷新的标记
let isRefreshing = false
    // 重试队列,每一项将是一个待执行的函数形式
let requests = []

instance.interceptors.response.use(
    response => {
        const data = response.data || {};
        const errorT = data.error || {};
        //22006
        if (data.success !== true && errorT.errorText && ![22006, 22001, 22002, 22005].includes(errorT.errorCode || 9999)) {
            MsgBox.error(errorT.errorText);
            // return;
        } else if (!data.success && [22001, 22006].includes(errorT.errorCode || 9999)) {
            let message = "用户过期或退出,重新登录";
            MsgBox.error(message);
            $requestLogin.toAuthLogin($routerT.currentRoute.fullPath);
            // return;
        } else if (errorT.errorCode === 22002) {
            // let message = "用token换取新的token";
            let tokenO = loginAuth.getToken() || {};
            // console.log(tokenO.refreshToken);
            const config = response.config;
            if (isRefreshing === false) {
                isRefreshing = true;
                console.log('refresh1');
                return refreshToken({
                    refreshToken: tokenO.refreshToken
                }).then(res => {
                    //直接跳转到登录/默认页面
                    let resultT = (res.data.error || {}).errorCode === 22005;
                    if (resultT !== true) {
                        //token获取成功,重新赋值
                        let dataT = res.data.data || {};
                        const token = {
                            tokenType: dataT.tokenType,
                            accessToken: dataT.accessToken,
                            expires: dataT.expires,
                            timeStamp: dataT.timeStamp,
                            refreshToken: dataT.refreshToken
                        };
                        const user = loginAuth.getUser();
                        loginAuth.saveAuth({}, user, token)
                            // 已经刷新了token,将所有队列中的请求进行重试
                        requests.forEach(cb => cb(user, token))
                        requests = []
                        return instance(config)
                    } else {
                        //直接退出,避免死循环
                        isRefreshing = false;
                        let message = "用户过期或退出,重新登录";
                        MsgBox.error(message);
                        $requestLogin.toAuthLogin($routerT.currentRoute.fullPath);
                    }
                }).catch(res => {
                    console.log(res)
                    window.location.href = '/'
                }).finally(() => {
                    // console.log(res)
                    isRefreshing = false;
                })
            } else {
                // console.log('refresh2');
                // 正在刷新token,将返回一个未执行resolve的promise
                return new Promise((resolve) => {
                    // 将resolve放进队列,用一个函数形式来保存,等token刷新后直接执行
                    requests.push((user, token) => {
                        loginAuth.saveAuth({}, user, token);
                        resolve(instance(config))
                    })
                })
            }
        } else if ((response.config.params || {})._localCacheKey && response.data && response.data.data && response.data.success === true) {
            // 存储本地 缓存key
            let localCacheKey = (response.config.params || {})._localCacheKey;
            // eslint-disable-next-line no-undef
            let $localforageCache = window.$localforageCache;
            // eslint-disable-next-line no-undef
            let timestamp = dayjs().valueOf();
            $localforageCache.setItem(localCacheKey, {
                data: response.data,
                timestamp: timestamp
            }).then(function() {
                bsLocalStorage.setLocalStore(localCacheKey, timestamp);
            }).catch(function(err) {
                console.log(err);
            });
        }
        return response
    }, error => {
        store.dispatch("dataLoading", false);
        MsgBox.error("请求超时");
        return Promise.reject(error)
    })

export default instance

头统一转换 req-headers.js

import {
  verifyApi
} from "./utils/guid-verify";
// import MsgBox from "./utils/msg-box";
import store from "./store/index";
import loginAuth from "./actions/login/auth";
/*
通过 jquery 同步 方式获取数据  通常用于登录认证
*/
export function $headers(headers = {}) {
  // let resData = {};
  headers = headers || {};
  //存放 Au
  let tempHeads = store.getters.headers;
  //设置默认头信息
  if (tempHeads) {
    let keys = Object.keys(tempHeads);
    for (let key of keys) {
      headers[key] = headers[key] || tempHeads[key];
    }
  }
  let token = loginAuth.getToken();
  // console.log(token);
  if (token) {
    // console.log(token.accessToken);
    let temp =
      token.tokenType + " " + token.accessToken;
    headers["Authorization"] = temp;
  }
  headers["XownerId"] = headers["XownerId"] || window.$appNavs.project.ownerId;
  headers["XverifyApi"] = verifyApi();
  headers["XfilterAreaCode"] = headers["XfilterAreaCode"] || window.$appNavs.area.defaultAreaCode;
  headers["XsysId"] = headers["XsysId"] || window.$appNavs.system.sysId;
  if (store.getters.location) {
    headers["XuserLat"] = store.getters.location.userLat;
    headers["XuserLng"] = store.getters.location.userLng;
  }
  //一级分享
  headers["XuserFromFirstShareId"] = store.getters.userFromFirstShareId || window.$sessionStorage.getSessionStore("userFromFirstShareId");
  //二级分享
  headers["XuserFromSecondShareId"] = store.getters.userFromSecondShareId || window.$sessionStorage.getSessionStore("userFromSecondShareId");
  if (!headers["Content-Type"] && !headers["Form-Content-Type"]) {
    headers["Content-Type"] = "application/json; charset=utf-8";
  }
  //当前语言
  headers["Xlang"] = window.$bowUtil.getLang();

  return headers;
}

XverifyApi信息获取 guid-verify.js


//,_security
import {
  encryptByDES
} from "./crypto";
//Guid 获取
export function newGuid() {
  let guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    let r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });

  if (window.$appNavs && window.$appNavs.project && window.$appNavs.project.ownerId) {
    let len = window.$appNavs.project.ownerId.length;
    guid = window.$appNavs.project.ownerId + '010' + guid.substr(0, guid.length - len - 3);
  }
  return guid;
}
//获取 VerifyApi 2分钟内有效
export function verifyApi() {
  /* eslint-disable */
  let result = null;
  if (
    window.$appNavs.auth.verifyApi === "only-guid") {
    result = encryptByDES(`${newGuid()}`);
  } else {
    result = encryptByDES(`${newGuid()}|${dayjs().add(110, 'second').valueOf()}`);
  }
  /* eslint-disable */
  return result;
}
// guid 参数
export function verifyGuid() {
  /* eslint-disable */
  let result = encryptByDES(`${newGuid()}`);
  /* eslint-disable */
  return result;

}

//控制特殊接口不受_menuId控制,只用于站内
export function verifyMenuId(menuId, userId, mkey, field) {
  return encryptByDES(`${userId}|${menuId}|${mkey}|${field}|${dayjs().add(6, 'second').valueOf()}`);
}


/**
 * 验证 number
 * @param {*} str 
 */
export function isNumber(str) {
  return Number.isNumber(str);
}

/**
 * 验证string
 * @param {*} str 
 */
export function isString(str) {
  return typeof str == "string" && str.constructor == String;
}


/**
 * 验证 array
 * @param {*} str 
 */
export function isArray(str) {
  return Array.isArray(str)
}


/**
 * 验证 object
 * @param {*} str 
 */
export function isObject(str) {
  return typeof str == "string" && str.constructor == String;
}
文档更新时间: 2023-01-31 12:43   作者:admin