Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs - http.createServer seems to call twice

Tags:

node.js

If I write the following program in node:

  http.createServer(function (req, res) {      if( req.method == 'GET' ) {       var body = ''; req.on('data', function(data) { body += data });       req.on('end',  function() {         console.log('request ended')       });     }      res.writeHead(200, {'Content-Type': 'text/plain'});     res.end('142\n');   }).listen(3500); 

And then hit the server with http://xxx.xx.xxx.xx:35010 I see a request ended twice on my console -- I'm not sure why a single HTTP request is causing this to execute twice.

like image 756
Will Avatar asked Aug 14 '12 22:08

Will


People also ask

What does createServer do in node JS?

createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.

Is createServer a callback function?

Like most Node. js functions, createServer() takes a callback function as an argument. This callback function is executed each time the server receives a new request.

How many requests per second can Nodejs handle?

However, considering that a “Hello World” Node. js server is easily capable of thirty thousand requests per second on that machine that produced these results, 23 requests per second with an average latency exceeding 3 seconds is dismal.

What are the parameters to the callback function of createServer () method?

createServer() passes two arguments to the callback when you call it. The first is the http request object, the second is the http response object. If your callback wants to work properly and use those arguments, it must create two arguments that match those. You can name them anything you want.


1 Answers

That is normal - your browser makes more than one call.

Most browsers make a call to grab /favicon.ico for example.

Try to log the url:

console.log(req.url); 

and you'll see what's being called.

like image 78
3on Avatar answered Oct 09 '22 04:10

3on