如何使用多个路由器文件

时间:2015-09-06 00:43:25

标签: node.js express

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

在我的app.js中,我有以下代码:

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

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

和controller / 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错误。

提前致谢。

4 个答案:

答案 0 :(得分:2)

请参阅How to include route handlers in multiple files in Express?

导出一个匿名函数,可以通过引用原始快速应用程序“启动”。

<强> ./控制器/ index.js

module.exports = function(app) {

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

<强> ./控制器/ 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 :(得分:2)

您的单节点应用程序必须具有单个路由器对象,路由器对象表示需要唯一端口的快速服务器。 因此,您应该在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');
    });
}

答案 2 :(得分:2)

假设“health.js”位于“controller”目录中,可能只是一个错字问题? var healthController = require('./controller/health/');有一个斜杠(/)。删除它会飞吗?所以它变成了var healthController = require('./controller/health');

答案 3 :(得分:0)

health.js中的更改:

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

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

可以正常运行。