Swagger未生成完整API路由请求的问题排查
这问题本质是swagger-autogen不会自动识别你在Express主文件里挂载的路由前缀(/client),它只会读取你在client-routes.js里定义的原始接口路径,所以生成的swagger_output.json里就只有/getRecord,没带上外层的/client前缀,导致Swagger UI发起请求时路径不全。
给你几个实用的解决办法:
在swagger-autogen配置里指定basePath
这是最推荐的方式,不用改路由文件,直接在生成swagger文档的代码里加个basePath配置,所有接口都会自动带上这个前缀。比如:const swaggerAutogen = require('swagger-autogen')(); const doc = { info: { title: '你的API文档', description: '接口描述' }, host: 'localhost:8080', basePath: '/client' // 这里加上你的路由前缀 }; const outputFile = './swagger_output.json'; const endpointsFiles = ['./client-routes.js']; swaggerAutogen(outputFile, endpointsFiles, doc);重新生成
swagger_output.json后,里面的接口路径就会变成/client/getRecord,Swagger UI发起请求时就会用完整路径了。直接在路由文件里给接口加前缀
如果你不想改swagger配置,可以把client-routes.js里的/getRecord改成/client/getRecord,但注意要同步修改Express主文件里的挂载代码——把app.use('/client', clientRoutes)改成app.use(clientRoutes),不然会出现/client/client/getRecord这种重复前缀的错误。不过这种方法不够灵活,以后要改前缀的话得改所有路由。检查Swagger UI的配置
如果你用的是swagger-ui-express,确保启动UI时没有额外覆盖路径配置,比如下面这种写法是正确的:const swaggerUi = require('swagger-ui-express'); const swaggerDocument = require('./swagger_output.json'); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));不需要在
setup里额外加前缀,因为swaggerDocument里已经通过basePath带上了/client。
内容的提问来源于stack exchange,提问作者ayowhatthedogdoin

