Pergunta

I'm trying to do something (which I hope) is simple: receive JSON from the a database and loop through it to create all the necessary page routes in Node.js. As of now, I'm just using stubbed data, but the console.log is always showing the last value "contact" in the key value pair. The first console displays everything correctly.

Here is my code:

routes = {
"Home" : "index.html",
"about" : "about.html",
"How it Works" : "how_it_works.html",
"contribute" : "contribute.html",
"contact" : "contact.html"
};

function routesGetandSet(data) {
  for (key in data) {
    console.log(key + "---" + '/' + data[key]);
    app.get('/' + data[key], function(req, res) {
      console.log(data[key]);
    });
  }
}

routesGetandSet(routes);

I thought this would be the easiest way to dynamically create page routes in Node (eventually I'll tie the data to in), but I could be wrong.

Can anyone point me the right direction? I am using the express framework.

Foi útil?

Solução

The problem is that the value of key in the closure is the same for all your routes (the value in the last iteration).

This should help explain how to create a new closure with a separate value in each one: http://www.mennovanslooten.nl/blog/post/62

Something like this should help:

for (key in data) {
  console.log(key + "---" + '/' + data[key]);
  (function(key1) {
    app.get('/' + data[key1], function(req, res) {
       console.log(data[key1]);
    });
   }
  )(key);
}

In the above code, key1 keeps a different value for each iteration in a separate closure.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top