node.js - 对除一个 Controller 之外的所有 Controller 使用快速中间件功能

标签 node.js express

我有一个应用程序,其 Controller 位于多个文件中,如下所示:

var aRoutes = require('./controllers/controllerA');
var bRoutes = require('./controllers/controllerB');
var cRoutes = require('./controllers/controllerC');

app.use('/a', aRoutes);
app.use('/b', bRoutes);
app.use('/c', cRoutes);
// ... several more

我有一个像这样的中间件功能......

app.use(function (req, res, next) {
    // do a middleware thing
    // but not if route == x or y or z or ... yuck!
});

我希望该中间件能够在除 aRoutes 之外的所有内容上运行。我看到了一个答案like this ,这建议在中间件 fn 中添加一个检查以排除每个路由,但我认为这很糟糕。可能有很多路由需要检查,当我添加其中一个异常路由时,它迫使我在两个地方触摸代码。

一定有更好的方法,对吗?

最佳答案

假设我理解正确,您可以通过重新排列中间件和路由的顺序来解决它。

var aRoutes = require('./controllers/controllerA');
var bRoutes = require('./controllers/controllerB');
var cRoutes = require('./controllers/controllerC');

app.use('/a', aRoutes);

app.use('/',function (req, res, next) {
    // do a middleware thing
    next();
});

app.use('/b', bRoutes);
app.use('/c', cRoutes);
// ... several more

现在,如果您使用 res.render 或其他结束请求-响应周期的操作而不是 next() 来结束 aRoutes ,中间件永远不会在aRoutes上运行。

但是它将在所有其他路线上运行。当然,只有当您希望中间件启动请求-响应周期时,这才有效。如果您想在其他地方使用它,则必须相应地重新排列代码。

关于node.js - 对除一个 Controller 之外的所有 Controller 使用快速中间件功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37263559/

相关文章:

javascript - Multer TypeError : fields. forEach 不是函数

node.js - Nodejs session 管理与 java 服务器 session 管理比较

javascript - Node js 将返回的 API key 存储为变量

javascript - 将文件发布到带有 Node 的 url

mysql - Sequelize : Parent with at least one children

node.js - Nodejs + Expressjs : Pass value in POST with Uploading of file

node.js - 购物。使用 shopify-node-api 更新元字段时出现问题

node.js - 为什么我的 socket.io 在服务器重新启动时获得连接?

node.js - 您如何对写入/读取 dynamodb 并通过 AWS API 网关端点调用的 NodeJs Lambda 函数进行单元测试?

javascript - 在我的服务器上安装/设置 Socket.IO