这是Express 4.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/Berlin
,req.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
中定义的版本号,因为功能可能不同。
答案 0 :(得分:1)
我有一个适合您需求的答案。由于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);