我正在与Swagger,Express和Node一起定义和运行端点。 localhost / docs上的GET请求返回所有相关的路由。但是,当我在任何一条路线上尝试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'));
});
});
在初始化中间件时,我尝试使用:
app.use(express.static(__dirname + './controllers'));
但是错误仍然存在。我认为这与路由有关,但我不确定错误在哪里。
该代码的目录结构为:
-my_app
|
+--controllers
| |
| +--user.js
| +--userService.js
+--index.js
最佳答案
尝试使用此构造
require('./controllers/<your_routing_file>')(app);
并输入不在index.js中的路由