如果未定义,则为全局变量设置默认值

Setting default value for global variable if undefined

Objective

userrole (e.g. admin) 传递给我所有的 view templates,而不必在每个单独的路线中都这样做。

我在尝试什么

将用户角色(使用 req.oidc.user... 调用)添加为 app.js 中的 res.local

代码 (app.js)

app.use((req, res, next) => {
  res.locals.role = req.oidc.user['https://localhost:3000.com/roles'] ?? "null"
})

问题

我希望 ?? "null" 会在用户未登录时向角色添加“空”值,这样我就可以使用

处理模板中的条件逻辑
'if !role === 'admin' do x. 

相反,我只是收到 Cannot read properties of undefined (reading 'https://localhost:3000.com/roles') 错误(可以理解,因为未登录时那里什么也没有!)

是否有更好的方法来传递在用户登录到我的视图之前未定义的值,而无需在 (controller.js) 中的每个路由中执行以下操作:

index = (req, res) => {
  res.render("index", {
    role: req.oidc.user['https://localhost:3000.com/roles'],
  });
};

如您所说,您的代码正试图从可能为 undefined.

的变量中读取一个值

您可以使用条件在读取之前检查 req.oidc.user 是否存在,或者使用 optional chaining 以便“short-circuit” undefined 的表达式没有导致错误。

这是带有可选链接的代码:

app.use((req, res, next) => {
    res.locals.role = req.oidc.user?.['https://localhost:3000.com/roles'] ?? "null";
});

旁注,我建议不要使用 "null" 作为默认值。也许使用空字符串 (""),它也是 falsy value.