引入 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);
  }
);
相关推荐
狼性书生4 小时前
uniapp实现的简约美观的星级评分组件
前端·uni-app·vue·组件
宇宙的最后一粒尘埃14 小时前
Typeerror: cannot read properties of undefined (reading ‘XXX‘)
vue
清幽竹客1 天前
vue-18(使用 Vuex 插件实现高级功能)
前端·vue.js·前端框架·vue
牧码岛1 天前
Web前端之隐藏元素方式的区别、Vue循环标签的时候在同一标签上隐藏元素的解决办法、hidden、display、visibility
前端·css·vue·html·web·web前端
MINO吖2 天前
基于 qiankun + vite + vue3 构建微前端应用实践
vue·vite·微前端·qiankun·single-spa
Luffe船长2 天前
elementUI点击浏览table所选行数据查看文档
javascript·elementui·vue
IT瘾君2 天前
JavaWeb:前端工程化-ElementPlus
前端·elementui·node.js·vue
sunbyte3 天前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | Dad Jokes(冷笑话卡片)
前端·javascript·css·vue.js·vue
幽络源小助理4 天前
SpringBoot+Vue+微信小程序校园自助打印系统
java·spring boot·微信小程序·小程序·vue
霸王蟹5 天前
从前端工程化角度解析 Vite 打包策略:为何选择 Rollup 而非 esbuild。
前端·笔记·学习·react.js·vue·rollup·vite