From f7cf768dc77feb06f993534d571d20142ee87454 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?old=E6=98=93?= <156663459@qq.com> Date: Wed, 9 Jul 2025 16:15:38 +0800 Subject: [PATCH] bug fixed --- server.js | 60 +++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 17 deletions(-) diff --git a/server.js b/server.js index d51eaed..2eac948 100644 --- a/server.js +++ b/server.js @@ -72,7 +72,6 @@ app.get('/mock-api/routes', (req, res) => { res.json(list); }); - // ✅ Swagger 配置 const swaggerDefinition = { openapi: '3.0.0', @@ -81,31 +80,35 @@ const swaggerDefinition = { version: '1.0.0', description: 'Dynamically registered mock APIs' }, - servers: [{ url: `http://192.168.100.138:${PORT}`, description: 'Local server' }] + servers: [] // 将由请求动态生成 }; function buildSwaggerSpecFromMocks(configs) { const paths = {}; - configs.forEach(({ method, path }) => { + configs.forEach(({ method, path, swagger }) => { const cleanPath = path.replace(/:([^/]+)/g, '{$1}'); const methodName = method.toLowerCase(); - paths[cleanPath] = paths[cleanPath] || {}; - paths[cleanPath][methodName] = { - summary: `Mocked ${method} ${path}`, - responses: { - 200: { - description: 'Mock response', - content: { - 'application/json': { - schema: { - type: 'object' - } - } + + const summary = swagger?.summary || `Mocked ${method} ${path}`; + const description = swagger?.description || ''; + const responses = swagger?.responses || { + 200: { + description: 'Mock response', + content: { + 'application/json': { + schema: { type: 'object' } } } } }; + + paths[cleanPath] = paths[cleanPath] || {}; + paths[cleanPath][methodName] = { + summary, + description, + responses + }; }); return { @@ -115,13 +118,36 @@ function buildSwaggerSpecFromMocks(configs) { } // ✅ Swagger UI 路由 +app.use('/swagger', (req, res, next) => { + res.setHeader('Cache-Control', 'no-store'); + next(); +}); + app.use('/swagger', swaggerUi.serve, (req, res, next) => { + const protocol = req.headers['x-forwarded-proto'] || req.protocol; + const host = req.get('host'); + + const dynamicSwaggerDefinition = { + ...swaggerDefinition, + servers: [ + { + url: `${protocol}://${host}`, + description: 'Current host' + } + ] + }; + const spec = buildSwaggerSpecFromMocks(mockConfigs); - swaggerUi.setup(spec)(req, res, next); + const dynamicSpec = { + ...spec, + servers: dynamicSwaggerDefinition.servers + }; + + swaggerUi.setup(dynamicSpec)(req, res, next); }); // ✅ 启动服务 app.listen(PORT, () => { console.log(`✅ Mock Server is running at http://localhost:${PORT}`); console.log(`📚 Swagger UI available at http://localhost:${PORT}/swagger`); -}); +}); \ No newline at end of file