Reputation: 143
Guys I have the following code which it supposed to increment a counter each time some one connect to server and post the message in the console but it increments only one time ,can you help me?
'use strict'
//Require express
var express=require('express');
//Trigger express
var app=express();
var counter=0;
//Set up the route URL
app.get('/', function(req, res){
res.send("<h1>You have connected</h1>");
});
//set up the port
app.listen(3000,function(){
//increment counter
counter+=1;
console.log("you have connected " + counter + " times");
})
Upvotes: 1
Views: 3212
Reputation: 1374
Ideally, you would need to add a listener to the 'connect' event (express object inherits from HTTP, so the server has this event) of the server, and increment the counter over there:
app.on('connect', function() {
counter++;
});
Hoe this helps.
Upvotes: 1
Reputation: 1535
You need to move your counter to inside the response.
app.get('/', function(req, res){
counter++;
res.send("<h1>You have connected "+counter+ " times </h1>");
});
This way whenever the page is loaded it will increment, not just when you boot it up and start listening with app.listen().
Upvotes: 1
Reputation: 1679
Well you have to store the counter variable in some persistant storage like a database or a textfile otherwise it will always be set to zero on each request
Upvotes: 0