引入 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);
  }
);
相关推荐
gc_229916 小时前
使用VS Code终端创建Vue项目报错:“npm : 无法加载文件 ...\npm.ps1,因为在此系统上禁止运行脚本”
vue·vs code
小阿鑫20 小时前
尤雨溪 : Vue 4 已经在规划中了!
vue·vite·vite+·程序员海军·vue4
离歌漠2 天前
《我用 Tauri 做了一个本地开发工具箱》
rust·typescript·vue
enjoy编程2 天前
playwright学习-I
typescript·vue·nodejs·1024程序员节·playwright
落花看风雪5 天前
从零开始搭建后台系统(vue3+TypeScript+Vite)01
typescript·vue·js
那年那棵树9 天前
基于WebGis的人生如旅地图系统
前端·arcgis·vue·课程设计
冒险的豆子12 天前
Vue2 、Vue3 响应式对比及优劣
vue
NetX行者13 天前
用 Vite + Vue3 + UnoCSS 搭建企业级项目模板(一):基础骨架
vue·vite·unocss
java水泥工13 天前
什么是前端
java·vue·html5
mont evergreen14 天前
一封从外部世界寄来的信:二维码数据如何穿越三重门,抵达你的屏幕
electron·vue·事件