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

标签 javascript node.js express

我是在搬石头砸自己的脚吗:

我想让 config、core 和 mean 在我的 Express 应用中的 app 和 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 访问它。

关于javascript - 将自定义属性添加到 Express 应用程序和请求。最好的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23716845/

相关文章:

javascript - jquery总计时间不正确

php - 显示带有数据库选择内容的警报

javascript - 我的代码在多个位置使用带有 key 的 API。如何在不上传 key 的情况下将代码上传到 GitHub?

angularjs - 安装 macOS Mojave 后 Node 和 npm 启动速度太慢

json - NodeJS-ExpressJS mongoose API POST 请求带外键

javascript - 扫雷算法解决方案

javascript - 将服务器端多个 HTTP 请求快速路由到第 3 方 API

node.js - 使用 .key 和 .crt 文件的 GoDaddy 证书在 Node 中使用 SSL

jquery - 在 ejs 模板中使用 jQuery

javascript - ExpressJS : Promises and Error Handling middleware