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

Setting global res.local variables on each request in express.js

本文关键字:全局 设置 res local 变量 请求 js express      更新时间:2023-09-26

基本上,我想构建一个站点范围的导航栏,其中包含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.router中间件之前运行所有app.use中间件。因此,我同意在代码的其他地方,您的代码片段中的app.use之前可能有一行app.use app.router