我是在搬石头砸自己的脚吗:
我想让 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/