引入 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);
  }
);
相关推荐
Lubase1 小时前
LuBase介绍&私有化部署教程
java·spring boot·低代码·gitee·vue
胡斌附体1 天前
vue打包测试环境
vue·打包·build·test·env环境文件
yyt3630458411 天前
K 线图高性能窗口化渲染
前端·javascript·css·vue.js·gitee·vue
天天开心a1 天前
【Vue错误修复】Vue模块居中问题
java·前端·javascript·vue.js·前端框架·vue
冥界摄政王2 天前
CesiumJS学习第四章 替换指定3D建筑模型
3d·vue·html·webgl·js·cesium
橘色的狸花猫2 天前
浪漫色彩下的博客系统
java·vue
千寻技术帮2 天前
10355_基于Springboot的驾校管理系统
spring boot·mysql·vue·文档·驾校管理
十铭忘2 天前
Vue3实现Pixso中的钢笔工具
开发语言·javascript·vue
wetyuo2 天前
【随手记】uniapp + V3 使用TailwindCss3
uni-app·vue·css3·vite
打工人小夏2 天前
前端面试题
前端·css·前端框架·vue·html·es6·html5