一个奇怪的SwaggerUI通过前端显示错乱的问题

现象

前端:框架为VUE3,构建工具Vite。
后端:Springboot3

访问:http://localhost:8080/swagger-ui/index.html,一切正常。
访问:http://localhost/api/swagger-ui/index.html,总是去解析https://petstore.swagger.io/v2/swagger.json,因而显示的也是官方petstore的示例文档。

查找问题步骤

前端vite.config.js片断:

1
2
3
4
5
6
7
8
9
10
11
server: {
port: 80,
host: true,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080/',
changeOrigin: true,
rewrite: (p) => p.replace(/^\/api/, ''),
}
},

这也没毛病啊。在前端访问所有/api前缀的URL,都会通过proxy去获取8080的内容,所以,http://localhost/api/swagger-ui/index.html 肯定是转到了 http://localhost:8080/swagger-ui/index.html ,没问题啊!

经过很多次debug,包括仅不限于:问各种AI、使用各种AI IDE(都交了钱)、去没落的stackoverflow、去官方github搜issue……,都无解。

最终解决方案

过程不表了,最终解决方案是,修改vite.config.js,增加关于 /v3 的代理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    server: {
port: 80,
host: true,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080/',
changeOrigin: true,
rewrite: (p) => p.replace(/^\/api/, ''),
+ },
+ '/v3': {
+ target: 'http://localhost:8080/',
+ changeOrigin: true,
+ }
}

原因

SwaggerUI的代码它要去读取/v3/api-docs/swagger-config,这是生成的html写死的,不转发/v3就找不到swagger-config,找不到它就——要么去显示官网的petstore,要么就直接显示”No API definition provided.”,取决于application.yml中springdoc.swagger-ui.disable-swagger-default-url设置的是true还是false。

参考资料
无。自己琢磨出来的