场景描述
在进行前后端项目开发时,一般使用axios请求后端接口数据。在这里有一个小问题,那就是使用时,我们要进行axios的配置,例如接口的url、请求参数、请求数据等等配置才能调用。有没有一种方法能根据后端接口直接生成接口,当我们前端需要调用时,直接传入请求参数后直接获取接口请求结果,无需其他配置呢?这就是我们要结束的前端接口自动生成。
前提
后端使用kinfe4j生成接口文档,如何knife4j如何引入,我这里简单介绍一下。
1、引入依赖
<!-- https://doc.xiaominfo.com/knife4j/documentation/get_start.html-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2、knife4j配置类(将包扫描路径basePackage设置为你的controller文件夹所在路径)
package com.yupi.springbootinit.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Knife4j 接口文档配置
* https://doc.xiaominfo.com/knife4j/documentation/get_start.html
*
* @author <a href="https://github.com/liyupi">程序员鱼皮</a>
* @from <a href="https://yupi.icu">编程导航知识星球</a>
*/
@Configuration
@EnableSwagger2
@Profile({"dev", "test"})
public class Knife4jConfig {
@Bean
public Docket defaultApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("接口文档")
.description("springboot-init")
.version("1.0")
.build())
.select()
// 指定 Controller 扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.yupi.springbootinit.controller"))
.paths(PathSelectors.any())
.build();
}
}
3、启动项目,访问 localhost:项目端口号/doc.html即可访问到接口文档
前端配置
1、安装所需要的请求库,我以axios为例
打开控制台,输入:yarn add axios
2、安装代码自动生成插件
npm install openapi-typescript-codegen --save-dev
3、全部安装完成后,在控制台输入
openapi --input http://localhost:8121/api/v2/api-docs --output ./generated --client axios即可自动生成接口文档
参数说明: input:后端接口地址;output: 前端接口文档生成位置;client:发送请求使用的库;
在实际使用时,需要将input地址改为你实际后端项目的地址(如 http://localhost:实际项目启动端口号/knife4j版本/api-docs)
4、按照步骤3完成后,可以看到前端项目多了一个接口文件。
在这个文件夹里就存储着后端接口。其中services文件夹里是我们的后端接口。在core文件夹里的OpenAPI文件中可修改请求的基本设置,如是否携带cookie,若要携带cookie,可将WITH_CREDENTIALS改为true,默认为false。
前端调用
后端接口如图所示
我们在前端调用时,只需用service.接口就可直接调用
如 TestControllerService.test({请求参数})即可调用成功。
总结
使用前端接口生成器可以是我们在前后端接口对接时一键生成可调用的接口,而且当后端接口发生变化时无需修改接口信息,有较强的灵活性。极大提高了前端开发效率。