简体   繁体   English

来自旧版本节点中数据库的动态路由

[英]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.

相关问题 如何使应用程序可以在旧版本的节点上运行 - How to make application runnable on older version of node 使用旧版本的节点创建 React App - Create React App with an older version of node 进行从节点到 mySQL 数据库的动态查询 - Making a dynamic query from node to a mySQL database Firebase 模块在部署功能时需要旧版本的节点 - Firebase module requires an older version of node while deploying the functions 根据数据库结果重新调整动态路由 - Restify dynamic routes based on database result Angular 2 Routes - 是否可以使用ngFor从路由创建动态routerLinks? - Angular 2 Routes - Is it possible to create dynamic routerLinks from routes, using an ngFor? 尝试使用 Node.js 动态路由从 IMDB 中抓取电影内容。 但是在我的 output.json 文件中未定义? - Trying to scrape movie contents from IMDB using Node.js dynamic routes . but getting undefined in my output.json file? 从json文件加载动态Vue路由 - Load dynamic Vue routes from json file 从数据 NuxtJS 创建动态路由 - Creating Dynamic Routes from data NuxtJS IE从11还原到旧版本以解决问题 - IE reverting from 11 to older version in order to fix issues
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM