创建中间件全局变量与局部变量

时间:2019-05-15 11:21:35

标签: javascript node.js express ejs

在研究如何更好地处理全球使用的数据期间,我发现了这个问题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模板中的两个对象吗?

1 个答案:

答案 0 :(得分:1)

执行此操作

res.locals = {
                // properties
            };

您将从先前的中间件调用中覆盖本地的先前值(因为您正在创建一个全新的对象)。您需要使用新值扩展res.locals,而不是创建一个全新的对象。为此,请使用Object.assign(),它将新值(第二个参数)与旧值(第一个参数)复制到对象中-请记住,如果它们的名称相同,则将覆盖它们! / p>

globalLocals: function (req, res, next) {
  res.locals = Object.assign(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 = Object.assign(res.locals, {
        index: "index2",
        loggedIn: req.user ? true : false,
        linkObj: await url.getAllUrl()
    });
    next();
}
相关问题