I'm currently using the Express router within a NodeJS application. I have simply been using app.use(app.router);
for routing and it works well.
However, I'm now testing out some new routes and want to handle them differently.
Ideally I would like to be able to say:
var vers2Router = require('./routes/version2');
app.use('/version2', vers2Router);
app.use(app.router);
Can I do this in order to handle all /version2
routes with vers2Router
and the rest simply using app.router
?
答案 0 :(得分:1)
自Express版本4.x起,app.router
已被删除。路线现在按照添加顺序执行。
现在您可以使用express.Router,因为它允许您拥有孤立的路由实例,在您的示例中,您可以使用自己的版本化路由创建许多路由器。
这样的事情:
// app.js
'use strict';
var express = require('express');
var app = express();
var userRouterV1 = require('./routes/v1/userRouter.js');
var userRouterV2 = require('./routes/v2/userRouter.js');
app.use('/v1/api/users', userRouterV1);
app.use('/v2/api/users', userRouterV2);
app.listen(4000, function () {
console.log('server up an running');
});
和你的孤立路线版本1:
// /routes/v1/userRouter.js
'use strict';
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('Hello v1');
});
module.exports = router;
最后你的孤立路线版本2:
// /routes/v2/userRouter.js
'use strict';
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('Hey v2');
});
module.exports = router;