添加自定义属性到Express应用程序和请求.最好的方法是什么?

Adding custom properties to Express app and req. What's the best way?

本文关键字:方法 是什么 请求 自定义属性 Express 应用程序 添加      更新时间:2023-09-26

我是不是搬起石头砸自己的脚:

我想让config, core和mean在我的Express应用程序和req对象上可用。

我使用的属性不在4。x的API。有什么我应该知道的吗?

是否有问题,只是添加它们作为属性?

// express.js
module.exports = function(db, config, meanModules) {
  var app = express();
  // ... 
  // Get mean-core
  var core = require('meanjs-core')(db, config);
  // Attach config, core, and modules to app    <==== POSSIBLE FOOT SHOOTING
  app.config = config;
  app.core = core;
  app.mean = meanModules;
  // Middleware to adjust req
  app.use(function(req, res, next) {
    // Add config, core, and modules to all requests  <==== POSSIBLE FOOT SHOOTING
    req.config = config;
    req.core = core;
    req.mean = meanModules;
    next();
  });
  // ...
}

我建议在应用程序中附加一个可能永远不会发生冲突的属性,并从那里访问所有内容,如app.myLibrary

app.myLibrary = {config: config, core: core, mean: meanModules};

从路由/中间件中访问app.myLibrary:

req.app.myLibrary

除非中间件中发生了动态变化,每个请求都不同,否则使用req.app.myLibrary访问它可能更好。