要在Node.js中使用swaggerJSDoc来生成swagger文档,可以按照以下步骤操作:
npm install swagger-jsdoc swagger-ui-express
const express = require('express');
const swaggerJSDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const app = express();
const port = 3000;
// Swagger文档配置
const swaggerOptions = {
swaggerDefinition: {
info: {
title: 'API文档',
version: '1.0.0',
description: 'API文档生成示例'
},
basePath: '/'
},
apis: ['./routes/*.js'] // 指定API路由文件的路径
};
// 生成swagger规范
const swaggerSpec = swaggerJSDoc(swaggerOptions);
// 使用Swagger UI中间件来提供API文档
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// 在此处定义API路由
// 例如:app.use('/api/users', require('./routes/users'));
// 启动服务器
app.listen(port, () => {
console.log(`服务器正在监听端口 ${port}`);
});
/**
* @swagger
* /api/users:
* get:
* summary: 获取所有用户
* description: 获取所有用户的列表
* responses:
* 200:
* description: 成功获取用户列表
*/
router.get('/api/users', (req, res) => {
// 处理获取用户列表的逻辑
});
node swagger.js
以上就是使用Node.js和swaggerJSDoc生成swagger文档的解决方法。务必根据自己的项目需求和API接口配置相应的swaggerOptions和路由。
上一篇:不生成随机数