express4路由器跳过基本路由并直接转到子路由

时间:2015-11-17 03:25:47

标签: node.js express routing routes

我有一个express4路由器,它正在跳过基本路由并直接转到指定的./user路由。但我不明白为什么它会跳过基本路线。

APP.js

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var router = express.Router();
var app = express();
require('./routes')(app);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//app.use('/', router);
module.exports = app;

./路由/ index.js

var express = require('express');
var router = express.Router();
// route middleware that will happen on every request
router.use(function(req, res, next) {
    // log each request to the console
    console.log(req.method, req.url);
    // continue doing what we were doing and go to the route
    next(); 
});
/* GET home page. */
router.get('/', function(req, res) {
    console.log('inside the root route');
});
//module.exports = router;
module.exports = function(app) {
    // here we list our individual sets of routes to use in the router
    require('./route/user')(app);
};

当我运行应用程序(npm start)时,控制台会显示位于用户路径内的日志,并完全跳过基本路径(' /')。

我哪里出错?

1 个答案:

答案 0 :(得分:1)

您似乎只是导出用户路线。 为了使这一点更清楚,当你需要routes.index.js时,app.js只能访问以下内容:

function(app) {
    // here we list our individual sets of routes to use in the router
    require('./route/user')(app);
};

因此它完全跳过基本路线的原因。

关注API documentation(在' express.Router'部分下),导出路线的正确代码是:

// exports the router.use and router.get('/) routes
module.exports = router

这意味着您必须将用户路由包含在其他部分(例如app.js)中。