Encapsulate Express Routers

孤街醉人 提交于 2019-12-11 01:25:45

问题


Is it possible to create different routers using Express.Router that don't share middleware?

To me it seems that Express.Router uses a singleton, so no matter what I try, the middleware gets attached to all routers. So, without having to create multiple instances of the Express app, is there a way to achieve the following:

Create mutliple routers

var router_a = Express.Router();
var router_b = Express.Router();

Give each router unique routes and middleware

router_a.use(function(req, res, next){
    console.log('Only works on router_a!');
});
router_a.get('/', function(req, res){
    console.log('Only works on router_a!');
});

router_b.use(function(req, res, next){
    console.log('Only works on router_b!');
});
router_b.get('/', function(req, res){
    console.log('Only works on router_b!');
});

Attach each route to a custom url namespace

app.use('/a', router_a);
app.use('/b', router_b);

Is there a straight forward way to achieve this? After reading through the docs on the Router I don't see anything that suggests such is possible.


回答1:


The one thing I see missing from your code is the call the next() in your middleware. If I add that to your code, it works perfectly fine for me.

The /b middleware is only called if the route starts with /b and same for the /a middleware with /a routes. And, to finish your code, you also have to send a response in your .get() handlers.

Here's the specific code I just tested:

var express = require('express');
var app = express();

var server = app.listen(80);

app.use(express.static('public'));

var router_a = express.Router();
var router_b = express.Router();

router_a.use(function(req, res, next){
    console.log('.use() - Only works on router_a!');
    next();
});
router_a.get('/', function(req, res){
    console.log('.get() - Only works on router_a!');
    res.send("router a, / route");
});

router_b.use(function(req, res, next){
    console.log('.use() - Only works on router_b!');
    next();
});
router_b.get('/', function(req, res){
    console.log('.get() - Only works on router_b!');
    res.send("router b, / route");
});

app.use('/a', router_a);
app.use('/b', router_b);


来源:https://stackoverflow.com/questions/34931196/encapsulate-express-routers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!