Kunok Kunok - 1 year ago 67
Javascript Question

Dynamic routes from database

I am using 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', {

However , no matter which url I access, I always get contents from last object in database.

So urls work, but code inside
callback function is not working properly. For example
variable is invalid, last object is displayed, rather than one matching path. If I would add this code:


as first line inside callback function, I would get next output:

Hitting first url:


Hitting second url:


Is there more convenient approach for dynamic routes and pages?

Answer Source

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:

Since let isn't supported in node, use an IIFE:

for (page of pages) {
    (function(p) {
        app.get(`/${p.path}`, (req, res)=> {
            res.render('test', {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download