封装快速路由器 [英] Encapsulate Express Routers

查看:44
本文介绍了封装快速路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用不共享中间件的Express.Router创建其他路由器?

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

在我看来,Express.Router使用单例,因此无论我尝试什么,中间件都将附加到所有路由器.因此,无需创建Express应用程序的多个实例,就可以实现以下目的:

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:

创建多路路由器

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

为每个路由器提供唯一的路由和中间件

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!');
});

将每条路由附加到自定义网址名称空间

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.

推荐答案

我发现代码中缺少的一件事是调用中间件中的 next().如果我将其添加到您的代码中,则对我来说效果很好.

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.

仅当路由以/b 开头并且与/a 中间件和/相同时,才调用/b 中间件.路线.而且,要完成代码,您还必须在 .get()处理程序中发送响应.

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);

这篇关于封装快速路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆