我通过将数据模型和路由拆分到单独的文件中,使Node.js应用程序模块化。
我的路线由express.Router()
导出。在这些路由中,我想从app.js导入查询的值以使用模板进行呈现。
我将如何用app.locals或req.variableName来最简单地保存内容?
由于使用express.Router()
的路由将其与app.js绑定在一起,因此我应该使用app.params()
并以某种方式使这些值可访问吗?
当我扩展应用程序时,使用全局变量似乎是一个更糟糕的主意。我不确定最佳实践是否会使用app.locals.valueKey = key.someValue
将值保存到流程环境中...
预先感谢任何人
最佳答案
如果我正确理解了这个问题,则希望将一个值传递给以后的中间件:
app.js:
// Let's say it's like this in this example
var express = require('express');
var app = express();
app.use(function (req, res, next) {
var user = User.findOne({ email: 'someValue' }, function (err, user) {
// Returning a document with the keys I'm interested in
req.user = { key1: value1, key2: value2... }; // add the user to the request object
next(); // tell express to execute the next middleware
});
});
// Here I include the route
require('./routes/public.js')(app); // I would recommend passing in the app object
/routes/public.js:
module.export = function(app) {
app.get('/', function(req, res) {
// Serving Home Page (where I want to pass in the values)
router.get('/', function (req, res) {
// Passing in the values for Swig to render
var user = req.user; // this is the object you set in the earlier middleware (in app.js)
res.render('index.html', { pagename: user.key2, ... });
});
});
});
关于node.js - 在Express中将变量传递到路由模板的最简单方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35076608/