发布于 2026-01-06 0 阅读
0

Swagger + Node.js (Express):分步指南

Swagger + Node.js (Express):分步指南

继之前关于为 SpringBoot 项目配置 Swagger 的文章之后,今天我将向大家介绍如何在 Node.js (Express) 项目中设置 Swagger 的分步指南。

1. 设置您的项目

首先,如果您还没有Node.js项目,请创建一个新的项目。

mkdir swagger-demo
cd swagger-demo
npm init -y
npm install express swagger-ui-express swagger-jsdoc

Enter fullscreen mode Exit fullscreen mode

2. 创建您的 Express 服务器

创建 index.js 文件(或 app.js 文件,取决于您的个人喜好):

touch index.js
Enter fullscreen mode Exit fullscreen mode
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');

const app = express();
const port = process.env.PORT || 3000;

// Swagger setup
const swaggerOptions = {
  swaggerDefinition: {
    myapi: '3.0.0',
    info: {
      title: 'My API',
      version: '1.0.0',
      description: 'API documentation',
    },
    servers: [
      {
        url: 'http://localhost:3000',
      },
    ],
  },
  apis: ['./routes/*.js'], // files containing annotations as above
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

// Sample route
app.get('/api/hello', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Enter fullscreen mode Exit fullscreen mode

3. 记录你的路线

创建一个名为 routes 的文件夹,并在其中添加一个 hello.js 文件(或其他任何路由文件):

mkdir routes
cd routes
touch hello.js
Enter fullscreen mode Exit fullscreen mode

然后,将以下代码添加到hello.js

/**
 * @swagger
 * /api/user:
 *   get:
 *     summary: Retrieve a list of users
 *     responses:
 *       200:
 *         description: A list of users
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   id:
 *                     type: integer
 *                     example: 1
 *                   name:
 *                     type: string
 *                     example: John Doe
 */
app.get('/api/user', (req, res) => {
  res.json([{ id: 1, name: 'John Doe' }]);
});
Enter fullscreen mode Exit fullscreen mode

4. 运行服务器

启动服务器:

node index.js

Enter fullscreen mode Exit fullscreen mode

5. 访问 Swagger UI

打开浏览器并访问http://localhost:3000/api-docs。您应该会看到包含 API 文档的 Swagger UI。

Swagger-javascript

按照这些步骤,您可以为您的 JavaScript 项目配置 Swagger,为您的开发团队和最终用户提供交互式 API 文档。

感谢阅读!我们下篇文章再见。

Swagger + SpringBoot 项目

文章来源:https://dev.to/cuongnp/swagger-nodejs-express-a-step-by-step-guide-4ob