how to attach middleware in swagger express like e

2019-08-15 03:11发布

问题:

I am trying to edit my express-swagger project and following this tutorial to add input validation into an express app

I used swagger-express-mw package to generate a boilerplate using swagger project create app but its not clear where I can add my middlewares as explained in the tutorial I mentioned above. Specifically i cant intercept my request, I get a typeError:

    TypeError: req.checkBody is not a function
     at saveNote 

Here is my entry file. Everything apart from the bodyParser and validator function is coming from the boilerplate so I dont understand

    SwaggerExpress.create(config, function(err, swaggerExpress) {
  if (err) { throw err }

  // install middleware
  swaggerExpress.register(app)
  // middleware
  app.use(bodyParser.urlencoded({ extended: false })); // my code
  app.use(validator()) // my d

  const port = process.env.PORT || 10010
  app.listen(port)


  // if (swaggerExpress.runner.swagger.paths['/notes']) {
  //   console.log('try this:\nlocalhost:10010/notes to get all notes')
  // }
})

回答1:

I know this is an old question, but this might help someone along the way.Here is the simple NodeJS code showing how to integrate swagger-tools with swagger-express-mw or swagger-node-runner npm packages.


var SwaggerExpress = require('swagger-express-mw');
var swaggerTools = require('swagger-tools');

var app = require('express')();
module.exports = app; // for testing

var config = {
    appRoot: __dirname // required config
};

SwaggerExpress.create(config, function(err, swaggerExpress) {
    if (err) {
        throw err;
    }

    // install middleware
    swaggerExpress.register(app);

    //swaggerobject is created by the swagger-express-mw module which is stored in runner object.
    var swaggerObjectLoaded = swaggerExpress.runner.swagger;

    //pass the runner object to initializeMiddleware function 
    swaggerTools.initializeMiddleware(swaggerObjectLoaded, function(middleware) {


        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());

        var port = process.env.PORT || 10010;
        app.listen(port);

        if (swaggerExpress.runner.swagger.paths['/hello']) {
            console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
        }
    });

});