我有一个基本的nodejs Restify 服务器,有两种简单的方法,一种是 GET ,一种是 POST 。我正在尝试在我的 Restify 服务之上添加 swagger API 文档。找到了对 Express 的支持。
还发现了一些库 https://www.npmjs.com/package/swagger-restify 。 但不知道如何在代码中使用它。如何以我所有的 api 文档都以“http://localhost:5000/docs”或类似的方式添加它。
我的基本 Restify 代码如下。
var restify=require('restify');
var restifyPlugins = require('restify-plugins');
var cors = require('cors');
var server=restify.createServer({name:'test'});
server.use(restifyPlugins.acceptParser(server.acceptable));
server.use(restifyPlugins.queryParser());
server.use(restifyPlugins.fullResponse());
server.use(restifyPlugins.bodyParser({
maxBodySize: 0,
multiples: true
}));
server.use(cors({
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials:'false',
optionsSuccessStatus: 200 /* some legacy browsers (IE11, various SmartTVs) choke on 204 */ ,
}))
server.use(restifyPlugins.authorizationParser());
server.get({path:'/test'},function(req,res,next){
console.log("TEST API")
res.send("hello");
});
server.post({path:'/postCheck'},function(req,res,next){
console.log("TEST post API",req.body.userId)
res.send("hello post");
});
server.listen(5000,function(){
console.log("Starting server at :%s,%s",server.url,server.name)
})
最佳答案
所以我确实设法将 Swagger 文档添加到我的 Node.js 和 Restify api 中。我希望有人觉得这很有帮助,并且没有什么被弃用的。
所以我使用的包名为restify-swagger-jsdoc
而且配置非常简单,您将需要
https://www.npmjs.com/package/restify-swagger-jsdoc
npm 我restify-swagger-jsdoc
然后在初始化 const server = Restify.createServer()
的文件中添加以下代码片段
const restifySwaggerJsdoc = require('restify-swagger-jsdoc');
restifySwaggerJsdoc.createSwaggerPage({
title: 'API documentation',
version: '1.0.0',,
server: server, // created restify server object,
path: '/api-docs', // url to view generated docs,
apis: ['./src/routes/*.js'], // this is where swagger can find
// files containing jsdoc or can point
// to api.yaml file
// to generate docs from.
});
一旦你运行你的服务器,并且你的 jsdoc swagger 注释和注释被添加到你的路由中,你应该能够在上面提到的路径中查看生成的 Swagger 文档。
关于node.js - 将 swagger 添加到我的 Nodejs Restify 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66167025/