user2480455
user2480455

Reputation: 11

Why the node.js script is call twice?

I am a beginner in Node.js I write the first script in Node.js like the below:

var count = 0;
var http = require('http');
var serv = http.createServer(function (req, res) {
    count++;
    console.log("why two?:" + count);
    res.writeHead(200,{'Content-Type': 'text/html'});
    require('colors');
    if (count % 2 == 0) {
        console.log('count:' + count);
        console.log('smashing node'.rainbow);
        res.end('<marquee>Smashing Node</marquee>');
    } else {
        console.log('count:' + count);
        console.log('WTF'.rainbow);
        res.end('<h4>Smashing Node</h4>');
    }
});
serv.listen(3000);

Then I run this script

node first.js

In browser, access http://localhost:3000 And the result in console is:

why two?:1
count:1
WTF
why two?:2
count:2
smashing node

Why the code is called twice? Thanks

Upvotes: 1

Views: 1671

Answers (3)

swarnava112
swarnava112

Reputation: 431

var count = 0;
var http = require('http');
var serv = http.createServer(); 
serv.on('request',function(req,res){
    count++;
    console.log("why two?:" + count);
    res.writeHead(200,{'Content-Type': 'text/html'});

    if (req.url=='/') {
        console.log(req.method);
        console.log(req.headers);
        console.log(req.url);
        res.end('<marquee>Smashing Node</marquee>');
    } 
});
serv.listen(3000);

in this it checks only for the '/' url and then responds....so the marquee is returned

Upvotes: 1

notgiorgi
notgiorgi

Reputation: 1771

That anonymous function is called whenever you request on http://localhost:3000

So maybe somehow you're requesting twice (e.g. for / and /favicon.ico) Try opening chrome dev tools, and in console tab you'll maybe see an error, that favicon.ico wasn't found.

or you can use morgan to keep track of requests:

var app = require('express')();
var morgan = require('morgan');
app.use(morgan('dev'));

It will log every request, with codes and URL-s. It needs express though.

Upvotes: 0

Quentin
Quentin

Reputation: 943537

Because two requests are being made.

Probably one is for / and the other is for /favicon.ico.

Your code doesn't care what the path is when it handles a request.

You can test that by looking in the Net tab of your browser's developer tools or examining the contents of the req object.

Upvotes: 6

Related Questions