我是 swagger 的新手,我已经编写了 swagger UI 文档的逻辑,但我需要将记录的 API 文档下载为 JSON 文件,你能帮我吗,谢谢。
const docs = require('./docs');
app.use('/api-docs',swaggerUI.serve,swaggerUI.setup(docs));
From ./docs.js
{
"openapi": "3.0.1",
"info": {
"version": "1.0.0",
"title": "NODE SERVICE",
"description": "This is a API docs",
"contact": {
"name": "Developer",
"email": "[email protected]",
"url": "https://mkibui.me"
},
"license": {
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
},
"servers": [
{
"url": "http://localhost:9090/api",
"description": "Local server"
}
],
"components": {},
"security": [
{
"bearerAuth": []
}
],
"paths": {}
}
}
我需要像这样下载 JSON 文件
A) 安装所需的包
npm install swagger-jsdoc swagger-ui-express
B) 在 Node 应用程序的根目录中创建一个名为 swagger.js 的新文件。
C) 将以下代码添加到 swagger.js 文件中。
const swaggerUi = require('swagger-ui-express');
const swaggerJSDoc = require('swagger-jsdoc');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'API Name',
version: '1.0.0',
description: 'API Description',
},
},
apis: ['**/*.js'], // Replace this with the path to your API routes
};
const swaggerSpec = swaggerJSDoc(options);
module.exports = (app) => {
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.get('/swagger.json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
});
};
要下载 Swagger JSON 文件,请转到 http://localhost:your-port/swagger.json。