【发布时间】:2019-10-02 12:40:34
【问题描述】:
在研究如何更好地处理全球使用的数据时,我发现了这个问题See 2. Answer
所以我将这种方法集成到我的代码基础中并提出了一个问题,我想讨论一下。希望有人可以在这里帮助我。
我创建了一个新文件middleware.js,其中包含与 SO 的答案几乎相同的代码,只是做了一些小的修改:
const url = require('../db/url');
module.exports = {
render: function (view) {
return function (req, res, next) {
res.render(view);
}
},
globalLocals: function (req, res, next) {
res.locals = {
title: "My Website's Title",
pageTitle: "The Root Splash Page",
author: "Cory Gross",
description: "My app's description",
};
next();
},
index: async function (req, res, next) {
res.locals = {
index: "index2",
loggedIn: req.user ? true : false,
linkObj: await url.getAllUrl()
};
next();
}
};
在我的 app.js 中,我包含了该文件并简单地告诉我的应用使用 globalLocals:
var middleware = require('./config/middleware');
app.use(middleware.globalLocals);
之后没有任何其他更改,我将其集成到我的 ejs template 中并且它起作用了:
<h1><%= title %></h1>
太棒了!
完成此操作后,我对中间件的 index 部分进行了一些尝试,并通过我的 app.js 集成了这个,但以不同的方式,因为我只想让这个“索引”变量可用于我的索引路由器,用于明确分离!
app.use("/", middleware.index, indexRouter);
所以现在我能够访问中间件中定义的值并在 ejs 中使用它们。但是我无法再访问我的任何globalLocals 并且我不明白为什么?
谁能告诉我如何保持上述分离并访问我的 ejs 模板中的两个对象?
【问题讨论】:
标签: javascript node.js express ejs