Http.Server does not have addListener in node.js? This is not an emitter of events?

I am just starting to play with node.js and was looking through the documentation. This code does not even run:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node.js\n');
}).listen(80, "127.0.0.1");
http.Server.addListener('request', function(req,res){
  console.log(req.headers);
});
console.log('Server running at http://127.0.0.1');

I am trying to add a listener to a server object for a request event. The "request" section of the document is listed as an event under http.Server.

Am I fundamentally misunderstanding something? How could you add a separate listener function to the request event? (i.e. do not overwrite added during createServer).

+3
source share
1 answer

It listendoes not seem to be chained, and you are not saving your server object. Try:

var http = require('http');
var myServer = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello Node.js\n');
});
myServer.listen(80, "127.0.0.1");
myServer.addListener('request', function(req,res){
    console.log(req.headers);
});

This is similar to my tests.

+5
source

All Articles