editor.swagger.io生成的ts文件的拦截器怎么写?

editor.swagger.io生成的ts文件的拦截器是哪个文件?
想在ts文件里也增加axios拦截器,代码该怎么写?

常见的axios拦截器是这样:

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: PATH_URL, // api 的 base_url
  timeout: config.request_timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (
      config.method === 'post' &&
      config!.headers!['Content-Type'] === 'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(config.data)
    }
    // get参数编码
    if (config.method === 'get' && config.params) {
      let url = config.url as string
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
    }
    //增加请求接口 头部信息
    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['token'] = getToken()
    // }
    return config
  },
  (error: AxiosError) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response: AxiosResponse<Recordable>) => {
    if (response.data.code === result_code) {
      return response
    } else {
      ElMessage.error(response.data.message)
    }
  },
  (error: AxiosError) => {
    console.log('err' + error) // for debug
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

export { service }

已经解决。

阅读 1.9k
1 个回答

myaxios.ts

import { ElMessage } from 'element-plus'
import globalAxios, { AxiosInstance } from 'axios';
import { decryptJWT, formatDate, formatDateEx } from './currency'

// token 键定义
const accessTokenKey = "access-token";
//const refreshAccessTokenKey = `x-${accessTokenKey}`;

const clearAccessTokens = () => {
  // 清除 token
  window.localStorage.removeItem(accessTokenKey);
  //window.localStorage.removeItem(refreshAccessTokenKey);
  //删除登录的用户信息
  window.sessionStorage.removeItem("userInfo");
  //跳转到登录页
  let str = window.location.href;
  const index = str.indexOf("/#");
  str = str.slice(0, index + 2);
  window.location.href = str + '/login'
  return

};

/**
 * axios 默认实例
 */
export const myAxiosInstance: AxiosInstance = globalAxios;

// 这里可以配置 axios 更多选项 =========================================

// axios 请求拦截
myAxiosInstance.interceptors.request.use(
  (conf) => {
    // 将 token 添加到请求报文头中
    conf.headers!["Authorization"] = `Bearer ${window.localStorage.getItem(
      accessTokenKey
    )}`;
    // conf.headers!["X-Authorization"] = `Bearer ${window.localStorage.getItem(
    //   refreshAccessTokenKey
    // )}`;

    // 这里编写请求拦截代码 =========================================
    const token: any = window.localStorage.getItem(accessTokenKey);

    if (token) {
      const aaa = decryptJWT(conf.headers!['Authorization']);
      //console.log(aaa);
      const s2 = formatDateEx(aaa.exp)
      //console.log(s2);
    }
    return conf;
  },
  (error) => {
    // 这里编写请求错误代码
    return Promise.reject(error);
  }
);

// axios 响应拦截
myAxiosInstance.interceptors.response.use(
  (res) => {
    console.log(res);
    
    // 401 登录已过期,请重新登录
    if (res.data.Code === 401) {
      //清空token并返回到登录页面
      clearAccessTokens();
    }

    // 处理未进行规范化处理的
    if (res.status >= 400) {
      throw new Error(res.statusText || "Request Error.");
    }    

    // 处理规范化结果错误
    if (res.data && res.data.hasOwnProperty("errors") && res.data.errors) {
      throw new Error(JSON.stringify(res.data.errors || "Request Error."));
    }

    // 读取响应报文头 token 信息
    const accessToken = res.headers[accessTokenKey];
    //const refreshAccessToken = res.headers[refreshAccessTokenKey];

    // 判断是否是无效 token
    if (accessToken === "invalid_token") {
      clearAccessTokens();
    }
    // 判断是否存在刷新 token,如果存在则存储在本地
    else if (
      //refreshAccessToken &&
      accessToken &&
      accessToken !== "invalid_token"
    ) {
      window.localStorage.setItem(accessTokenKey, accessToken);
      //window.localStorage.setItem(refreshAccessTokenKey, refreshAccessToken);
    }

    // 这里编写响应拦截代码 =========================================
    
    //成功
    if (res.status === 200 && res.data.Code == 200) {
      //其他返回      
      return res.data
    } else if (res.status === 200 && res.data.Code == 204) {
      //注册账户返回
      ElMessage.success(res.data.message)
      return res.data
    } else {      
      //失败返回
      ElMessage.error(typeof res.data.message == "object" ? res.data.message.confirm[0] : res.data.message)
      return res.data
    }

  },
  (error) => {
    // 这里编写响应错误代码
    return Promise.reject(error);
  }
);

base.ts

/* tslint:disable */
/* eslint-disable */
/**
 * 通用权限管理平台
 * 前后端分离架构,开箱即用,紧随前沿技术。<br/><a href='https://gitee.com/zuohuaijun/Admin.NET/'>https://gitee.com/zuohuaijun/Admin.NET</a>
 *
 * OpenAPI spec version: 1.0.0
 * 
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */
import { Configuration } from "./configuration";
// Some imports not used depending on template conditions
// @ts-ignore
import globalAxios, { AxiosRequestConfig, AxiosInstance } from 'axios';
import { myAxiosInstance } from "@/utils/myaxios"

export const BASE_PATH = "http://47.112.143.149/YNYC/Product/www/service".replace(/\/+$/, "");

/**
 *
 * @export
 */
export const COLLECTION_FORMATS = {
    csv: ",",
    ssv: " ",
    tsv: "\t",
    pipes: "|",
};

/**
 *
 * @export
 * @interface RequestArgs
 */
export interface RequestArgs {
    url: string;
    options: AxiosRequestConfig;
}

/**
 *
 * @export
 * @class BaseAPI
 */
export class BaseAPI {
    protected configuration: Configuration | undefined;

    constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = myAxiosInstance) {
        if (configuration) {
            this.configuration = configuration;
            this.basePath = configuration.basePath || this.basePath;
        }
    }
};

/**
 *
 * @export
 * @class RequiredError
 * @extends {Error}
 */
export class RequiredError extends Error {
    name: "RequiredError" = "RequiredError";
    constructor(public field: string, msg?: string) {
        super(msg);
    }
}

decryptJWT

export function decryptJWT(token: string): any {
  token = token.replace(/_/g, "/").replace(/-/g, "+");
  const json = decodeURIComponent(escape(window.atob(token.split(".")[1])));
  return JSON.parse(json);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题