2017-08-08 81 views
2

我正在使用Swagger,Express和Node來定義和運行端點。 localhost/docs上的GET請求返回所有相關路由。但是,當我嘗試在任何路線的GET請求,返回 「無法獲取/ XXX」Swagger,Express和Node.js中的「無法獲取/」

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')); 
    }); 



}); 

雖然初始化中間件,我嘗試使用:

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

但是錯誤仍然存​​在。我認爲這與路由有關,但我不確定錯誤在哪裏。

的代碼目錄結構:

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

回答

0

嘗試使用這種結構

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

和類型的路線不index.js

相關問題