ruoyi前后端分离访问swagger
时间: 2023-09-01 11:12:59 浏览: 108
RuoYi前后端不分离项目整合LDAP
ruoyi的前后端分离可以通过以下步骤访问swagger。
1. 后端配置
在ruoyi-admin模块中的Swagger2Config类中,将api-docs的访问路径设置为全局跨域访问:
```
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.**.controller"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(false)
.enableUrlTemplating(true)
.globalResponseMessage(RequestMethod.GET, responseMessages())
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.enable(true);
}
private List<ResponseMessage> responseMessages() {
List<ResponseMessage> responseMessages = new ArrayList<>();
responseMessages.add(new ResponseMessageBuilder().code(404).message("资源不存在").build());
responseMessages.add(new ResponseMessageBuilder().code(400).message("请求参数错误").build());
responseMessages.add(new ResponseMessageBuilder().code(500).message("服务器内部错误").build());
return responseMessages;
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList = new ArrayList<>();
apiKeyList.add(new ApiKey("token", "token", "header"));
return apiKeyList;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build());
return securityContexts;
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return new ArrayList<>(Arrays.asList(
new SecurityReference("token", authorizationScopes)));
}
```
2. 前端配置
在ruoyi-admin模块的/src/main/resources/application.yml文件中,添加以下配置:
```
cors:
allowed-origins: '*'
allowed-methods: GET, POST, PUT, DELETE, OPTIONS
allowed-headers: '*'
exposed-headers: Authorization, Token, Content-Disposition
max-age: 1800
```
3. 访问swagger
然后,在浏览器中访问`http://localhost:8080/swagger-ui.html`,即可访问swagger。如果出现跨域问题,可以参考以上配置进行调整。
阅读全文