站酷网素材图库免费下载,wordpress发表的文章百度抓取失败,网站建设和管理自查报告,wordpress网址导航开源在后端开发完接口之后#xff0c;前端如果再去写一遍接口来联调的话#xff0c;会很浪费时间#xff0c;这个时候使用OpenAPI接口文档来生成Axios接口代码的话#xff0c;会大大提高我们的开发效率。
Axios引入
Axios是一个基于Promise的HTTP客户端#xff0c;用于浏览器…在后端开发完接口之后前端如果再去写一遍接口来联调的话会很浪费时间这个时候使用OpenAPI接口文档来生成Axios接口代码的话会大大提高我们的开发效率。
Axios引入
Axios是一个基于Promise的HTTP客户端用于浏览器和Node.js。它可以在浏览器中发送异步HTTP请求并且支持处理请求和响应的拦截器、请求和响应的转换、取消请求等功能。Axios具有简洁的API设计易于使用和集成到各种前端框架和项目中。
在Vue中使用Axios可以方便地进行与我们的后端API的通信。下面是在Vue中使用Axios的步骤 安装Axios首先你需要在项目中安装Axios。你可以使用npm或yarn进行安装例如 npm install axios导入Axios在main.ts导入Axios库 import axios from axios;发送HTTP请求可以使用Axios发送HTTP请求 axios.get(/api/users).then(response {// 处理成功响应console.log(response.data);}).catch(error {// 处理错误console.error(error);});
上述代码中我们使用axios.get方法发送一个GET请求到/api/users接口并使用.then和.catch方法处理成功和错误响应。 设置请求和响应拦截器Axios允许你在请求发送之前和响应返回之后拦截并处理请求和响应。可以使用axios.interceptors来设置请求和响应拦截器。我们可以在Vue组件的生命周期钩子中设置拦截器 axios.interceptors.request.use(config {// 在发送请求之前做些什么return config;
}, error {// 处理请求错误return Promise.reject(error);
});axios.interceptors.response.use(response {// 对响应数据做些什么return response;
}, error {// 处理响应错误return Promise.reject(error);
});
上述代码中我们使用axios.interceptors.request.use方法设置请求拦截器在发送请求之前可以对请求进行一些处理。类似地我们使用axios.interceptors.response.use方法设置响应拦截器在接收到响应后可以对响应进行处理。这只是Axios在Vue中的基本用法示例更多的可以参考Axios的官方文档https://axios-http.com/ 引入ApenAPI-TypeScript-Codegen
这个nodejs库可以帮助我们根据后端的接口文档生成对应的联调代码无需再手动写一遍提高我们的开发效率使用地址ferdikoomen/openapi-typescript-codegen: NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification (github.com) 安装
npm install openapi-typescript-codegen --save-dev
详细的help介绍
$ openapi --helpUsage: openapi [options]Options:-V, --version output the version number-i, --input value OpenAPI specification, can be a path, url or string content (required)-o, --output value Output directory (required)-c, --client value HTTP client to generate [fetch, xhr, node, axios, angular] (default: fetch)--name value Custom client class name--useOptions Use options instead of arguments--useUnionTypes Use union types instead of enums--exportCore value Write core files to disk (default: true)--exportServices value Write services to disk (default: true)--exportModels value Write models to disk (default: true)--exportSchemas value Write schemas to disk (default: false)--indent value Indentation options [4, 2, tab] (default: 4)--postfixServices Service name postfix (default: Service)--postfixModels Model name postfix--request value Path to custom request file-h, --help display help for commandExamples$ openapi --input ./spec.json --output ./generated$ openapi --input ./spec.json --output ./generated --client xhr
之后我们去看一下后端的Knife4j接口文档: 去浏览器输入这个localhost:9090/api/v2/api-docs 如果显示这个则没问题接下来在前端项目的终端输入指令
openapi --input http://localhost:9090/api/v2/api-docs --output ./generated --client axios
就会自动生成联调接口的代码 这个时候我们在到代码中去引用就可以发送请求给后端了