Javascript 在express.js中为每个请求设置全局res.local变量

Javascript 在express.js中为每个请求设置全局res.local变量,javascript,node.js,coffeescript,express,pug,Javascript,Node.js,Coffeescript,Express,Pug,基本上,我想构建一个站点范围的导航栏,其中包含express.js中的局部变量中指定的链接 因此,我建立了我想要包含在页面上的链接列表: class NavigationLink constructor: (@title,@url) -> app.use (req,res,next) -> res.locals.navigationLinks = [ new NavigationLink "About", "/about" new NavigationLin

基本上,我想构建一个站点范围的导航栏,其中包含express.js中的局部变量中指定的链接

因此,我建立了我想要包含在页面上的链接列表:

class NavigationLink
  constructor: (@title,@url) ->

app.use (req,res,next) ->
  res.locals.navigationLinks = [
    new NavigationLink "About", "/about"
    new NavigationLink "Projects", "/projects"
    new NavigationLink "Skills", "/skills"
    new NavigationLink "Contact", "/contact"
  ]
  next()
然后,如果我点击主页:

app.get '/', (req,res) ->
  res.render('about')
Jade尝试渲染此布局文件,该文件应在navigationLinks数组中循环并渲染每个布局文件:

!!! 5
html
include header
body
    .container
        .row
            .span3
                ul.nav.nav-tabs.nav-stacked
                    for navigationLink in navigationLinks
                        include navigationLink
            .span9
                block content

然而,我得到了一个参考错误“navigationLinks未定义”,我假设这意味着本地人没有通过。我想知道如何解决这个问题,或者其他更适合这种情况的设计模式(在网站的每个页面上动态构建链接)。谢谢

Jonathan Ong是正确的。上面的代码应该以默认的中间件顺序工作,该顺序将运行所有
应用程序。在
应用程序路由器
中间件之前使用
中间件。因此,我同意在你的代码的其他地方,你可能有一行
app.use app.router
,在
app.use
之前。在你的代码片段中使用

我猜你的
app.use
app.router
下面。好的,所以我已经验证了我之前的代码在我把app.router放在它下面的时候是有效的。Peter使用app.locals的原始代码也有效。按照惯例,哪种方式更好?App.locals还是像我上面所做的那样设置res.locals?
res.locals
对于您的
/weather
路线中特定于此请求的数据(如
res.locals.currentTemp
)更有意义
app.locals
更适合大多数或所有视图需要的内容。在您的情况下,如果大多数视图使用相同的布局,则使用
app.locals.navigationLinks