I'm brand new to Node.js and I'm having a small issue which might have something to do with my understanding of Node.
Basically, I'm trying to create a bunch of severs (each one on a different port) to emulate a situation where my app would be calling out to multiple clients. However, when I loop, I'm trying to make them have an endpoint that returns their "ID", but for some reason it always returns the final value of i, 19, rather than the index that I stored during with client.set during the loop. Am I missing something simple? Here's my server.js:
var express = require('express');
var clientcount= 20;
var clients= new Array();
for (var i=0; i < clientcount; i++) {
var client= express();
client.set('id', i);
client.get('/', function(req,res) {
console.log("Pinged " + client.get('id'));
res.send("Hello world from " + client.get('id'));
});
clients.push(client);
console.log("Test value: " + clients[i].get('id'));
clients[i].listen(3001 + i);
console.log("Client listening on port " + (3001 + i));
}
In this example, the "Test Value" prints out as expected, but if I use postman to hit say, 127.0.0.1:3014, I get 19 instead of 13 as expected.