【问题标题】:Access express application from middleware从中间件访问 express 应用程序
【发布时间】:2017-01-22 14:01:41
【问题描述】:

我有一个中间件,我这样称呼它:

app.use(example({optiona:'abc'}));

我想从中间件函数访问应用程序,然后执行另一个 app.use,如下所示:

module.exports = function (options){
    app.use(...);
    return function(req, res, next)
        next();
}

我知道将应用程序传递给导出的选项,但我想在没有传递它的选项的情况下执行它,或者将其设置为全局..

【问题讨论】:

  • 您在req.app 中有可用的app
  • 我想一般设置一个中间件,而不是在每个请求上都设置它(“app.use”)
  • 请阅读中间件的工作原理:expressjs.com/en/guide/using-middleware.html
  • 我知道它是如何工作的。我想在use函数里面访问app,声明多个中间件..

标签: node.js express connect middleware


【解决方案1】:

您可以尝试将 Express 路由器作为一个选项 (read all about it)。

基本上,您可以保持您的第一件相同:

app.use(example({optiona:'abc'}));

然后您可以在函数中执行以下操作:

var express = require("express");
var router = express.Router();

module.exports = function(options) {
    // You can declare middleware specific to this router
    router.use(...);

    // You can declare routes specific to this router
    router.get("/foo", ...);
    router.all("/bar", ...);

    // Then just return the router at the end
    return router;
}

路由器允许您相应地使用自己的路由/中间件设置“子应用程序”。

【讨论】:

    猜你喜欢
    • 2021-05-30
    • 2023-03-21
    • 1970-01-01
    • 2019-03-18
    • 2013-11-30
    • 2019-10-30
    • 2019-09-26
    • 2018-08-25
    • 2022-01-06
    相关资源
    最近更新 更多