引入 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);
  }
);
相关推荐
iRuriCatt17 小时前
智慧景区管理系统 | 计算机毕设项目
java·前端·spring boot·vue·毕设
吹牛不交税19 小时前
admin.net框架使用记录
vue·.netcore
是梦终空1 天前
计算机毕业设计263—基于Springboot+Vue的影视推荐和评分系统(源代码+数据库)
spring boot·vue·毕业设计·课程设计·协同过滤算法·影评系统·影视推荐系统
EstherNi1 天前
小程序中,下拉多选的组件,有写死的三级下拉,样式需要修改
javascript·小程序·vue
青春男大2 天前
已有后端基础学习前端简单页面交互
前端·javascript·学习·typescript·vue
shejizuopin2 天前
基于Spring Boot的高校科研管理系统的设计与实现(毕业论文)
java·spring boot·vue·毕业设计·论文·毕业论文·高校科研管理系统的设计与实现
皮卡穆2 天前
Vue3 + Swiper.js 实现无缝轮播图组件
前端·javascript·vue
泰勒疯狂展开3 天前
Vue3研学-组件的生命周期
开发语言·前端·vue
千寻技术帮3 天前
10392_基于SpringBoot的大学迎新系统
mysql·vue·源码·springboot·代码·新生报到
总爱写点小BUG4 天前
VU-Icons:打造极致体验的 Vue3 & UniApp 双端 SVG 图标库
uni-app·vue·组件库·图标组件库