简体   繁体   中英

“Cannot get /” in Swagger, Express and Node.js

I am working with Swagger, Express and Node to define and run endpoints. A GET request on the localhost/docs returns all the relevant routes. But when I try a GET request on any of the routes, it returns a "Cannot Get /XXX"

Index.js

'use strict';

var fs = require('fs'),
path = require('path'),


// Basic Setup new express
http     = require('http'),
express  = require('express'),
mysql    = require('mysql'),
parser   = require('body-parser');


var swaggerTools = require('swagger-tools');
var jsyaml = require('js-yaml');



// Setup express
var app = express();
app.use(parser.json());
app.use(parser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 5000);

// Database Connection
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'sample_database'
});
try {
    connection.connect();
  console.log('Database connected!');

} catch(e) {
    console.log('Database Connetion failed:' + e);
}

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

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

  // Create server
  http.createServer(app).listen(app.get('port'), function(){
    console.log('Server listening on port ' + app.get('port'));
  });



});

While initialising the middleware, I tried using:

app.use(express.static(__dirname + './controllers'));

But the error is still present. I think this has got something to do with the routing but I am not sure where is the error is.

The directory structure for the code is:

-my_app
  |
  +--controllers
  |  |
  |  +--user.js
  |  +--userService.js
  +--index.js

Try use this construction

require('./controllers/<your_routing_file>')(app);

and type routes not in index.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM