gpt4 book ai didi

javascript - 创建中间件 Global vs local var

转载 作者:行者123 更新时间:2023-11-30 19:33:56 26 4
gpt4 key购买 nike

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

最佳答案

当你这样做的时候

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

关于javascript - 创建中间件 Global vs local var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56148162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com