引入 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);
  }
);
相关推荐
万亿少女的梦16810 小时前
基于Vue、Vite与CesiumJS的江西省铜矿资源WebGIS系统设计
vue·vite·cesiumjs·webgis·空间数据可视化
天丁o17 小时前
我把一套 Flowable + Spring Boot + Vue 的 BPM 流程引擎整理开源了:从流程设计器到待办闭环
spring boot·vue·工作流引擎·flowable·bpm流程引擎·流程审批
弹简特17 小时前
【Vue3速成】05-vue3官方库路由机制之路由守卫
vue·路由
小堂子这厢有礼了1 天前
Chet.Admin 模块详解⑥:字典管理 + useDict 联动表单
vue·后台管理系统·vbenadmin·chet.admin
猫猫不是喵喵.1 天前
Vue3 hooks 函数
vue
Pu_Nine_94 天前
Vue3+TS+Express 转 Nuxt4 全栈开发笔记(Drizzle ORM + MySQL)
前端·vue·express·nuxt.js·全栈框架
shmily麻瓜小菜鸡4 天前
vue3里“devDependencies 是开发环境依赖,dependencies 是生产环境依赖”
前端·javascript·vue.js·vscode·vue·angular.js
脾气有点小暴4 天前
ECharts 伪 3D 柱状图完整注释 + 实现原理说明
前端·3d·信息可视化·vue·echarts
sugar__salt4 天前
Vue3 核心特性深度解析:v-model、ref 属性与 nextTick 完全指南
前端·javascript·vue.js·前端框架·vue
勇往直前plus6 天前
Vue3(篇四)单页面应用到路由管理
javascript·typescript·前端框架·vue