引入 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);
  }
);
相关推荐
IT教程资源C20 小时前
(N_122)基于springboot,vue网上订餐系统
mysql·vue·前后端分离·网上订餐系统·springboot网上订餐
星光一影1 天前
美容/心理咨询/问诊/法律咨询/牙医预约/线上线下预约/牙医行业通用医疗预约咨询小程序
mysql·小程序·vue·php·uniapp
yuyu_03041 天前
SOHE智能厨余垃圾处理系统
java·vue
Watermelo6171 天前
【前端实战】从 try-catch 回调到链式调用:一种更优雅的 async/await 错误处理方案
前端·javascript·网络·vue.js·算法·vue·用户体验
狼性书生1 天前
uniapp实现的时间范围选择器组件
前端·uni-app·vue·组件·插件
Irene19912 天前
CLI 与 Vite 创建项目对比(附:最优解 create-vue)
vue·vite·cli·项目创建
全栈前端老曹2 天前
【前端权限】 权限变更热更新
前端·javascript·vue·react·ui框架·权限系统·前端权限
今天不要写bug3 天前
基于qrcode前端实现链接转二维码的生成与下载
前端·javascript·typescript·vue
剑小麟3 天前
vue2项目中安装vant报错的解决办法
vue.js·java-ee·vue
你真的可爱呀3 天前
4.前后端联调(Vue3+Vite + Express + MySQL)
mysql·node.js·vue·express