引入 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);
  }
);
相关推荐
格子软件7 小时前
2026年GEO优化系统源码的分布式状态机深度拆解
java·前端·vue.js·vue·geo
格子软件8 小时前
2026年GEO优化系统源码解构:核心状态机与高并发流控深度剖析
java·vue.js·spring boot·vue·geo
蜡台10 小时前
Node 安装 awesome-qr 失败解决
javascript·vue·qrcode·awesome-qr
格子软件10 小时前
2026年GEO优化系统源码级状态机与多模型调度拆解
java·前端·vue.js·人工智能·vue·geo
格子软件15 小时前
2026年分布式GEO优化系统源码状态机深度拆解实录
java·前端·vue.js·vue·geo
格子软件17 小时前
格子GEO优化系统源码深度解析:从零搭建AI驱动的内容矩阵
java·vue.js·人工智能·spring boot·vue·geo
小葛要努力19 天前
安装nvm 管理node.js版本实现vue2和vue3项目共存
node.js·vue·nvm
这里是杨杨吖19 天前
SpringBoot+Vue高校在线考试系统 附带详细运行指导视频
vue·在线考试·springboot
wuxia211820 天前
在5种环境中编写点击元素改变内容和颜色的JavaScript程序
javascript·微信小程序·vue·jquery·react
Sweet锦20 天前
Vue3 集成 ApexCharts 避坑指南:从动画失效到自定义指令的完美解决方案
vue·echarts