前端 Express 框架 Swagger 多接口编写及路径请求
在使用 Swagger 编写 API 文档时,可以将不同请求路径的 API 接口放入不同的文件中,这样可以避免覆盖的情况。例如,可以按照模块或功能将 API 接口分别放入不同的文件中。
对于如何在 Express 框架中使用 Swagger 编写 API 文档,可以参考以下步骤:
- 安装
swagger-jsdoc和swagger-ui-express模块
npm install swagger-jsdoc swagger-ui-express --save
- 创建 Swagger 配置文件
在项目根目录下创建一个 swagger.js 文件,用于配置 Swagger。配置文件中需要指定 API 文档的基本信息、文档生成路径、API 接口路径等信息。
const swaggerJSDoc = require('swagger-jsdoc');
const options = {
swaggerDefinition: {
// 基本信息
info: {
title: 'API 文档',
version: '1.0.0',
description: 'API 文档'
},
// 服务器信息
servers: [{
url: 'http://localhost:3000',
description: '本地服务器'
}]
},
// API 接口路径
apis: ['./routes/*.js']
};
const swaggerSpec = swaggerJSDoc(options);
module.exports = swaggerSpec;
- 在 Express 中使用 Swagger
在 Express 应用程序中引入 swagger-ui-express 模块,并将 Swagger 配置文件作为参数传递给 swaggerUi.setup() 函数。然后,在需要展示 API 文档的路由中使用 swaggerUi.serve() 和 swaggerUi.setup() 函数即可。
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./swagger');
const app = express();
// 展示 API 文档
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// 其他路由
app.listen(3000, () => {
console.log('服务器已启动');
});
- 编写 API 接口
在 routes 目录下创建一个 api.js 文件,用于编写 API 接口。在 API 接口中,可以使用 Swagger 注释来描述接口的请求方式、请求参数、响应结果等信息。
/**
* @swagger
* /api/users:
* get:
* summary: 获取所有用户
* description: 获取所有用户
* responses:
* 200:
* description: 成功返回
* content:
* application/json:
* schema:
* type: object
* properties:
* code:
* type: number
* description: 响应状态码
* example: 200
* data:
* type: array
* description: 用户列表
* items:
* type: object
* properties:
* id:
* type: number
* description: 用户 ID
* example: 1
* name:
* type: string
* description: 用户名
* example: '张三'
*/
router.get('/api/users', (req, res) => {
// API 接口实现
});
在以上示例中,使用了 @swagger 注释来描述了 API 接口的请求方式、请求参数、响应结果等信息。在 Swagger 配置文件中,使用了 apis 属性来指定 API 接口所在的文件路径。在使用 Swagger 展示 API 文档时,Swagger 会自动根据注释中的信息生成 API 文档。
原文地址: https://www.cveoy.top/t/topic/lExk 著作权归作者所有。请勿转载和采集!