[英]Dynamic routes from database in older version of node
I am using Node.js v ~4. 我正在使用Node.js v〜4。
I am trying to build routes by using objects from database. 我正在尝试通过使用数据库中的对象来构建路由。 This is my logic:
这是我的逻辑:
for (page of pages) {
app.get(`/${page.path}`, (req, res)=> {
res.render('test', {
page:page,
})
})
}
However , no matter which url I access, I always get contents from last object in database. 但是,无论我访问哪个url,我总是从数据库中的最后一个对象获取内容。
So urls work, but code inside app.get()
callback function is not working properly. 因此url可以工作,但是
app.get()
回调函数中的代码无法正常工作。 For example page
variable is invalid, last object is displayed, rather than one matching path. 例如
page
变量无效,显示最后一个对象,而不是一个匹配路径。 If I would add this code: 如果我要添加以下代码:
console.log(req.url);
console.log(page.path);
as first line inside callback function, I would get next output: 作为回调函数中的第一行,我将获得下一个输出:
Hitting first url: 到达第一个网址:
/test01
test03
Hitting second url: 到达第二个网址:
/test02
test03
Is there more convenient approach for dynamic routes and pages? 动态路由和页面是否有更方便的方法?
You need an to use
let
on your variable being iterated over to preserve the scope - else it'll always bind the route to the last item being iterated over:
您需要在要迭代的变量上使用
let
来保留作用域-否则它将始终将路由绑定到要迭代的最后一个项目:
Since let
isn't supported in node, use an IIFE: 由于节点中不支持
let
,因此请使用IIFE:
for (page of pages) {
(function(p) {
app.get(`/${p.path}`, (req, res)=> {
res.render('test', {
page:p,
})
})
})(page)
}
This works for me: 这对我有用:
router.get('/:page', function (req, res) {
var page = req.params.page;
if (pages.indexOf(page) === -1) res.redirect('/');
else res.render('index', {title: page});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.