要解决API端点文档不显示使用Swagger和Express的问题,可以按照以下步骤进行操作:
npm install swagger-ui-express swagger-jsdoc express --save
const express = require('express');
const swaggerUI = require('swagger-ui-express');
const swaggerJSDoc = require('swagger-jsdoc');
const app = express();
// Swagger配置
const swaggerOptions = {
swaggerDefinition: {
info: {
title: 'API 文档',
description: 'API 文档描述',
version: '1.0.0',
},
},
apis: ['path/to/api/routes.js'], // 替换为您的API路由文件路径
};
const swaggerDocs = swaggerJSDoc(swaggerOptions);
// 使用Swagger UI中间件
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocs));
// 其他Express中间件和路由
// ...
// 启动Express服务器
app.listen(3000, () => {
console.log('服务器已启动在端口3000');
});
/**
* @swagger
* /api/users:
* get:
* summary: 获取所有用户
* description: 获取所有用户的信息
* responses:
* 200:
* description: 成功获取用户列表
*/
app.get('/api/users', (req, res) => {
// 处理获取用户的逻辑
// ...
res.send('获取用户列表');
});
/api-docs
端点来查看Swagger生成的API文档。例如:http://localhost:3000/api-docs
。通过以上步骤,您应该能够解决API端点文档不显示使用Swagger和Express的问题,并且能够正确生成和展示API文档。