wujingjing
2024-07-18 cf7eda004123f2ee07bfa7d05f51f71f9dbb4bcd
src/utils/request.ts
@@ -4,36 +4,57 @@
import emitter from './mitt';
import { debounce } from './util';
import { AUTH_URL, MAIN_URL, SECONDARY_URL } from '/@/constants';
import { Local, Session } from '/@/utils/storage';
import { Local, LoginInfo, Session } from '/@/utils/storage';
import { LOGIN_URL } from '../api/ai/user';
import { NO_AUTH_API_LIST } from '../api/ai/chat';
// import JSONbig from 'json-bigint';
//#region ====================== 后端 res.err_code ======================
export const enum ErrorCode {
   /** @description 权限验证失败 */
   Message = 'MESSAGE',
   /** @description 内部错误 */
   Exception = 'EXCEPTION',
   /** @description 无权使用 */
   Auth = 'AUTH',
}
//#endregion
const handleNoAuth = debounce(() => {
const emitNoAuth = () => {
   emitter.emit('logout');
   emitter.emit('openLoginDlg');
};
export const handleNormalAuth = () => {
   const accessSession = Local.get(accessSessionKey);
   if (!accessSession) {
      emitter.emit('logout');
      emitter.emit('openLoginDlg');
   }
   return !!accessSession;
};
const handleNoAuth = debounce(() => {
   emitNoAuth();
});
const loginUrl = '/login';
const initRequestInterceptor = (request: AxiosInstance) => {
   // 添加请求拦截器
   request.interceptors.request.use(
      (config) => {
         // 获取本地的 token
         const accessSession = Local.get(accessSessionKey);
         if (accessSession) {
            // 将 token 添加到请求报文头中
            config.headers['hswatersession'] = accessSession;
         } else {
            if (config.url !== loginUrl) {
               handleNoAuth(config.url);
               throw '权限验证失败';
         if (!NO_AUTH_API_LIST.includes(config.url)) {
            if (accessSession) {
               // 将 token 添加到请求报文头中
               config.headers['hswatersession'] = accessSession;
            } else {
               if (config.url !== LOGIN_URL) {
                  handleNoAuth(config.url);
                  throw '权限验证失败';
               }
            }
         }
         return config;
      },
      (error) => {
@@ -71,25 +92,26 @@
                     handleNoAuth();
                     throw '权限验证失败';
                  }
                  break;
               case ErrorCode.Exception:
                  ElMessage.error('内部错误!');
                  throw '内部错误';
            }
            const msg = serveData.json_msg ?? '';
            const error = serveData?.err_code ? `${msg ? `【${serveData.err_code}】` : serveData.err_code}` : '';
            const tip = error + msg || '请求失败';
            ElMessage.error(tip);
            const url = res.request.responseURL;
            throw new Error(url + '\n' + tip);
         }
         return res.data;
      },
      (error) => {
         if (typeof error === 'string') {
            // ElMessage.error(error);
            return Promise.reject(error);
         }
         // 处理响应错误
         if (error.response) {
            if (error.response.status === 401) {
               clearAccessTokens();
            }
         }
         // 对响应错误做点什么
         if (error.message.indexOf('timeout') != -1) {
            ElMessage.error('网络超时');
@@ -138,19 +160,33 @@
 * @description 域名前缀
 * 防止类似于 http://sqi.beng35.com/airp 和 http://sqi.beng35.com/test 公用同一个 token 或 userInfo
 */
const subDomainName = window.location.pathname
   .split('/')
   .filter((item) => !!item)
   .join('-');
const domainPrefix = subDomainName ? `${subDomainName}-` : '';
export const getDomainPrefix = (win: Window) => {
   const subDomainName = win.location.pathname
      .split('/')
      .filter((item) => !!item)
      .join('-');
   const domainPrefix = subDomainName ? `${subDomainName}-` : '';
   return domainPrefix;
};
// token 键定义
export const accessSessionKey = domainPrefix + 'access-session';
export const userNameKey = domainPrefix + 'userName';
export const sessionName = 'access-session';
export const userName = 'userName';
export const getSessionKey = (win: Window) => {
   return getDomainPrefix(win) + sessionName;
};
export const getUserNameKey = (win: Window) => {
   return getDomainPrefix(win) + userName;
};
export const accessSessionKey = getSessionKey(window);
export const userNameKey = getUserNameKey(window);
export const refreshAccessTokenKey = `x-${accessSessionKey}`;
// userInfo键定义
export const userInfoKey = domainPrefix + 'userInfo';
export const userInfoKey = getDomainPrefix(window) + 'userInfo';
// 获取 token
export const getSession = () => {
@@ -159,7 +195,8 @@
// 清除 token
export const clearAccessTokens = async () => {
   Local.remove(accessSessionKey);
   // Local.remove(accessSessionKey);
   LoginInfo.remove();
   // 清除用户信息(每次刷新都需要利用用户信息去请求对应权限菜单)
   Local.remove(userInfoKey);
   // 清除其他