这是Express4.x。让他们拥有以下架构:

server.js

var express = require('express');
var mainRouter = express.Router();
var subRouter = express.Router();

subRouter.route('/').get(function(req, res, next) {
    console.log(req.params);
});

mainRouter.use('/:username', subRouter);

app.use('/', mainRouter);


然后我打电话给GET /Amberlamps。我希望req.params{ username: 'Amberlamps' },但是我得到的是{}

但是,如果我将subRouter中的路线更改为:

subRouter.route('/:city').get(function(req, res, next) {
    console.log(req.params);
});


并调用GET /Amberlamps/Berlinreq.params{ city: 'Berlin' }

如何获得:username

编辑:根据要求,我想解释一下,为什么我要使用路由器作为subRouter

假设我要使用以下架构构建RESTful api服务器:

[path_to_api_server]/[version]/[resource]
http//api.example.com/1/users

server.js

mainRouter.use('/:version/items', itemsRouter);
mainRouter.use('/:version/messages', messagesRouter);
mainRouter.use('/:version/users', usersRouter);

app.use('/', mainRouter);


usersRouter.js

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

usersRouter.route('/')
  .get(getUser)
  .post(postUser)
  .put(putUser)
  .delete(deleteUser);

module.exports = usersRouter;


这样做的好处是,每个资源路由器都可以工作,而无需知道它正在侦听的路径。但是,资源路由器需要知道:version中定义的版本号,因为功能可能有所不同。

最佳答案

我有一个适合您的答案。由于subRouter由mainRouter封装,因此无权访问version,因此添加一个中间件,该版本会将版本从main传递到subRouter。

var express = require('express');
var mainRouter = express.Router();
var subRouter = express.Router();

var app = express();

var apiRoutes = {
    itemRouter : function(req, res, next){
        console.log('/items','version',req.version,req.params);
        next();
    },
    messagesRouter : function(req, res, next){
        console.log('/messages','version',req.version,req.params);
        next();
    },
    usersRouter : function(req, res, next){
        console.log('/users','version',req.version,req.params);
        next();
    }
}

subRouter.route('/items/:id').get(apiRoutes.itemRouter);
subRouter.route('/messages/:id').get(apiRoutes.messagesRouter);
subRouter.route('/users/:id').get(apiRoutes.usersRouter);

//attach a middleware that will pass through the version to the subrouter via the request object
mainRouter.use('/:version', function(req, res, next){
    console.log('version', req.params.version);
    req.version = req.params.version;//pass version via req object
    next();
});

//attach your subRouter
mainRouter.use('/:version',subRouter)

app.use('/', mainRouter);

app.listen(3000);

10-08 05:00