【问题标题】:Creating Middleware Global vs local var创建中间件全局与本地变量
【发布时间】: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


    【解决方案1】:

    当你这样做时

    res.locals = {
                    // properties
                };
    

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

    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();
    }
    

    【讨论】:

    • 这完全有道理,不知道我是怎么错过的。非常感谢,成功了!
    猜你喜欢
    • 1970-01-01
    • 2022-06-11
    • 2018-08-31
    • 2016-10-25
    • 2013-11-28
    • 2017-11-12
    • 2020-08-01
    • 2015-03-24
    • 2013-03-23
    相关资源
    最近更新 更多