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



目标

userrole (e.g. admin)传递给我的所有view templates,而不必在每个单独的路由中执行。

我在尝试什么

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

代码(app.js)

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

问题

我希望CCD_ 7将增加值"0";空";当用户没有登录时,我可以使用处理模板中的条件逻辑

'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的变量中读取一个值。

您可以在读取CCD_ 11之前使用一个条件来检查它是否存在;"短路";将表达式转换为CCD_ 12而不会引起错误。

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

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

附带说明,我建议不要使用"null"作为默认值。也许使用一个空字符串(""),它也是一个错误值。

最新更新