mercredi 18 février 2015

How to create routes dynamically with express.js?


I've created a small node.js application which uses express for routing. I'm trying to create my different routes in a dynamic/iterative way that goes something like this:



var places = {};

places['home'] = { name: 'home', greeting: 'Hello from home'};
places['work'] = { name: 'work', greeting: 'Hello from work'};
places['park'] = { name: 'park', greeting: 'Hello from park'};

var router = express.Router();
for (var place in places) {
router.get('/' + places[place].name, function(req, res) {
res.send(places[place].greeting);
});
}


My little app seems to be serving http calls very well, but for some reason, the routes are giving me trouble. In the code example above I always seem to get the response of the very last route created inside that loop, even though it correctly handles the calls for any of those three route names. This is the output that I get:



http://localhost:3000/.../home --> //Output = 'Hello from park'
http://localhost:3000/.../work --> //Output = 'Hello from park'
http://localhost:3000/.../park --> //Output = 'Hello from park'


All three calls are handled but all three give me the same output, which should only be correct when I call 'park'.


I'm fairly new in these technologies so I must be missing something really obvious. Or is there another way to create these routes dynamically?





Aucun commentaire:

Enregistrer un commentaire