nodejs的express与swagger结合使用的方法

nodejs的express与swagger结合使用的方法


如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033

文章目录

  • nodejs的express与swagger结合使用的方法
    • @[toc]
    • 前言
    • 代码

环境:
nodejs : 12.13.0
express : 4.16.3
swagger-editor : 2.4.9

可以解决的问题:

  1. nodejs文件管理与接口管理服务
  2. url(包括正则方式)拦截

前言

Swagger 是一款RESTFUL接口的、基于YAML、JSON语言的文档在线自动生成、代码自动生成的工具。

Express 是一个保持最小规模的灵活的 Node.js Web 应用程序开发框架,为 Web 和移动应用程序提供一组强大的功能。

Swagger和Express组合在一起,可以灵活的解决很多问题。例如,使用Express进行文件的管理,使用Swagger进行接口的管理。

代码

'use strict';

var fs = require('fs');
var path = require('path');
var http = require('http');

const express = require('express')(); // express

var app = require('connect')();
var swaggerTools = require('swagger-tools');
var jsyaml = require('js-yaml');
var serverPort = 8080;

// swaggerRouter configuration
var options = {
    swaggerUi: path.join(__dirname, '/swagger.json'),
    controllers: path.join(__dirname, './controllers'),
    useStubs: process.env.NODE_ENV === 'development' // Conditionally turn on stubs (mock mode)
};

// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
var spec = fs.readFileSync(path.join(__dirname, 'api/swagger.yaml'), 'utf8');
var swaggerDoc = jsyaml.safeLoad(spec);

// 下载文件  // express
express.get('/apkUpdate/*', function (req, res, next) {
    var f = req.params[0];
    f = path.resolve(f);
    console.log('Download file: %s', f);
    res.download(f);
});

// 不以/docs开头的文件  // express
express.get("^(?!/docs)*.*", function (req, res) {
    console.info("1_" + req.url);

    var f = req.path;
    f = __dirname + f;
    console.log('Download_1 file: %s', f);
    res.download(f);
})

//  express
express.get("/*", function (req, res) {
    console.debug("0_" + req.url);
    app(req, res);
})

// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {

    // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
    app.use(middleware.swaggerMetadata());

    // Validate Swagger requests
    app.use(middleware.swaggerValidator());

    // Route validated requests to appropriate controller
    app.use(middleware.swaggerRouter(options));

    // Serve the Swagger documents and Swagger UI
    app.use(middleware.swaggerUi());

    // respond to all requests
    app.use(function (req, res) {
        res.end('Hello from Connect!\n');
    });

    // Start the server
    http.createServer(express).listen(serverPort, function () {  // express
        console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
        console.log('Swagger-ui is available on http://localhost:%d/docs', serverPort);
    });

});

觉得文章对你有帮助,可以扫描二维码捐赠给博主,谢谢!
在这里插入图片描述
如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:129518033


License

License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎


Reference:

  1. https://swagger.io/
  2. http://www.expressjs.com.cn/

你可能感兴趣的:(NodeJS)