2015-09-06 51 views
0

如何使用多個路由器文件使用快速框架?如何使用多個路由器文件

在我app.js,我有以下代碼:

var controller = require('./controller/index'); 
var healthController = require('./controller/health/'); 

app.use('/', controller); 
app.use('/health', healthController); 

和控制器/ index.js:

var express = require('express'); 
var router = express.Router(); 

/* GET home page. */ 
router.get('/', function(req, res, next) { 
    res.render('index'); 
}); 

module.exports = router; 

而且health.js:

var express = require('express'); 
var router = express.Router(); 

/* GET health confirmation. */ 
router.get('/health', function(req, res, next) { 
    res.send('OK'); 
}); 

module.exports = router; 

當我打了http://localhost:8000/,我得到正確的頁面沒有任何問題,但是,http://localhost:8000/health導致404錯誤。

在此先感謝。

+1

假設「health.js」駐留在「控制器」目錄中,可能它只是一個錯字問題? ''var healthController = require('./ controller/health /');''有一個尾部斜線(/)。刪除它會飛?所以它變成''var healthController = require('./controller/health');'' – tiblu

+0

@tiblu你能否發佈這個答案,以便我可以接受它爲你的功勞? :-) – Srikrishnan

+0

好的,不客氣! – tiblu

回答

2

假設「health.js」駐留在「控制器」目錄中,可能只是一個錯字問題? var healthController = require('./controller/health/');有一個尾部斜線(/)。刪除它會飛?所以它變成var healthController = require('./controller/health');

1

參見How to include route handlers in multiple files in Express?

導出可以通過引用原始快速應用程序「啓動」的匿名函數。

./controller/index.js

module.exports = function(app) { 

    /* GET home page. */ 
    app.get('/', function(req, res, next) { 
     res.render('index'); 
    }); 
}; 

./controller/health.js

module.exports = function(app) { 

    /* GET health confirmation. */ 
    app.get('/health', function(req, res, next) { 
     res.send('OK'); 
    }); 
}; 

./app.js

var app = require('express')(); 

var controller = require('./controller/index'); 
var healthController = require('./controller/health'); 

controller(app); 
healthController(app); 
1

您的s單節點應用程序必須具有單個路由器對象,路由器對象表示需要唯一端口的快遞服務器。 因此,您應該在您的app.js中將路由器對象傳遞給所有路由器文件。

代碼就會像 -

app.js

var express = require('express'); 

var router = express.Router(); 

var controller = require('./controller/index'); 
var healthController = require('./controller/health/'); 

controller(router); 
healthController(router); 

index.js

module.exports = function(router) { 
    router.get('/', function(req, res, next) { 
     res.render('index'); 
    }); 
} 

health.js

module.exports = funtion(router) { 
    router.get('/health', function(req, res, next) { 
     res.send('OK'); 
    }); 
} 
相關問題