gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 00:46:29 25 4
gpt4 key购买 nike

基本上我想构建一个站点范围的导航栏,其中包含在 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 is not defined”,我认为这意味着本地人没有通过。会喜欢关于如何解决问题的建议,或者更适合这种事情的另一种设计范例(在网站的每个页面上动态构建链接)。谢谢!

最佳答案

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

关于javascript - 在 express.js 中为每个请求设置全局 res.local 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12118392/

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