我刚刚通过将数据模型和路由分成单独的文件来制作Node.js应用程序模块。
我的路线由express.Router()
导出。在这些路线中,我想从我的app.js中导入查询值,以便使用模板进行渲染。
我如何以最简单的方式保存事物,请说app.locals或req.variableName?
由于使用express.Router()
的路由与app.js绑定在一起,我应该使用app.params()
并以某种方式使这些值可访问吗?
使用全局变量似乎是一个更糟糕的主意,因为我正在扩展应用程序。我不确定最佳做法是使用app.locals.valueKey = key.someValue
...
非常感谢任何人
答案 0 :(得分:0)
如果我正确理解了这个问题,您希望将值传递给以后的中间件:
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, ... });
});
});
});