Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

node.js - Why the callback function gets called twice for each request?

Guys I am new to node js and this behavior is strange to me! In the code snippet below,

'use strict';
var http = require('http');
var numberOfRequests = 0;
http.createServer(function (request, responce) {
    console.log('Request number ' + numberOfRequests + ' received!');
    responce.writeHead(200);
    responce.write("Here is responce to your request..");
    responce.end();
    numberOfRequests++;
}
).listen(8080);
console.log('listening ...');

for each

localhost:8080 

call at Chrome, the app writes twice onto console? e.i for a single 8080 call, it prints out:

Request number 0 received!
Request number 1 received!

I am using Visual studio to run this node js app.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Usually, when you see two requests for each page request, one is for the desired page and one is for the favicon for the website. This is what most browsers do unless there is meta tag in the page that tells the browser not to request a favicon resource. If you do this in your handler:

console.log(request.url)

That will likely show you what's going on. In general, you don't want to have a web server where you never look at what resource is being requested. If you based your logic on a specific resource being requested such as /, then you would easily be able to ignore other types of requests such as the favicon.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...