0

I trying to find my way into node.js transfering a local sports statistics application written in c#.

Writing the http server, i observe that every time i refresh (after the first time) the server to make a new request, i have 2 response.

I strip the code to eliminate every other possible cause and the "problem" still exists.

Code

var http = require("http");
var counter = 0;
var port = process.env.PORT || 3000;
var requestListener = function (req, res) {
    counter += 1;
    res.end("Hits: "+ counter);
};

var server = http.createServer(requestListener);

server.listen(port, function (err) {
    console.log("server listen on port " + port);
});

Is this the normal behaviour or i missing something?

1 Answers1

3

In a browser page, this is often caused by the browser requesting your page and then requesting some other resource from the same host (such as the favicon for the page). You can see exactly what is being requested to shine some light on what's happening by logging req.url:

var http = require("http");
var counter = 0;
var port = process.env.PORT || 3000;
var requestListener = function (req, res) {

    // add logging for what url is being requested
    console.log(req.url);

    counter += 1;
    res.end("Hits: "+ counter);
};

var server = http.createServer(requestListener);

server.listen(port, function (err) {
    console.log("server listen on port " + port);
});

Is this the normal behaviour or i missing something?

This is normal and expected. If the extra request turns out to be a favicon request, then you can disable that as explained here: How to prevent favicon.ico requests?

Note: it is a bit unusual to have a web server that does not even look at the requesting URL and does the same thing no matter what path request was sent to it. If you were looking at the URL and branching your code based on the URL, you would likely be avoiding requests that you were not expecting.

jfriend00
  • 683,504
  • 96
  • 985
  • 979