引入 axios,根据 api 文档生成调用接口

起步 | Axios Docs

安装 axios

复制代码
npm install axios

生成 api 调用接口【可选】

https://github.com/ferdikoomen/openapi-typescript-codegen

  1. 安装

    npm install openapi-typescript-codegen --save-dev

  2. 然后执行生成代码

    http://localhost:8805/api/user/v3/api-docs:这个是接口文档url【返回的json】

    ./generated: 代表的是生成的路径

    axios: 指定的客户端 axios

    openapi --input http://localhost:8805/api/user/v3/api-docs --output ./generated --client axios

  1. 测试

    import { Swagger3Service } from '../generated/services/Swagger3Service'

    setTimeout(() => {
    Swagger3Service.test()
    }, 1000)

如果想要自定义请求参数,怎么办?

使用代码生成器提供的全局参数修改对象

https://github.com/ferdikoomen/openapi-typescript-codegen/blob/master/docs/openapi-object.md

复制代码
export const OpenAPI: OpenAPIConfig = {
  BASE: 'http://localhost:3000/api',
  VERSION: '2.0',
  WITH_CREDENTIALS: false,
  CREDENTIALS: 'include',
  TOKEN: undefined,
  USERNAME: undefined,
  PASSWORD: undefined,
  HEADERS: undefined,
  ENCODE_PATH: undefined,
};

直接定义 axios 请求库的全局参数,比如全局请求响应拦截器

Interceptors | Axios Docs

复制代码
import axios from "axios";

axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
axios.interceptors.response.use(
  function (response) {
    console.log("响应", response);
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);
相关推荐
Leaderxin3 小时前
还在用 Electron?6 种跨平台桌面方案横评:Rust + Vue 把安装包从 224MB 干到 4.7MB
rust·vue·跨平台·tauri·桌面应用
YWL3 小时前
vue-time-axis-plus进阶:双进度条+跨空白续播+播放指针,打造专业级监控回放体验
前端·javascript·vue·时间轴
尾善爱看海4 天前
Vue 面试进阶篇:Composition API、插槽、自定义指令……8 个章节 + 高频面试题全解析
前端·javascript·vue.js·面试·vue
明耀4 天前
vue chart 强行刷新高度,宽度
vue
YWL5 天前
OpenLayers弹窗Overlay深度实战
前端·vue·openlayers
YWL5 天前
OpenLayers+ECharts联动:地图点击联动图表,数据可视化大屏方案
前端·信息可视化·vue·echarts·openlayers
YWL5 天前
OpenLayers地图分享:URL参数同步+分享链接生成,让用户一键分享地图视角
前端·javascript·vue·openlayers
程序员蜡笔熊6 天前
Vite 8 换芯实测:Rolldown 替掉双引擎,构建快 3.19 倍
前端·javascript·vue
YWL7 天前
OpenLayers导出功能:地图截图+GeoJSON导出完整方案,从Canvas合并到PDF生成
前端·vue·openlayers
上单带刀不带妹7 天前
小程序图片缓存问题:时间戳和版本号解决图片不更新
缓存·小程序·vue·uniapp