Ishan Patel
Ishan Patel

Reputation: 6091

how to log all properties of the reqest object in node.js?

I am new to learning node.js and curious about what kind of data that req parameter would have while any request hit the server. I have tried For loop, but it doesn't seem to logging anything.

var http = require('http');

var server = http.createServer(function( req, res){
  for (var key in req) {
    if (req.hasOwnProperty(key)) {
        console.log(key + " -> " + req[key]);
    }
}

      res.end("Hi there \n");
});

server.listen(3000, function(){
    console.log('Server on 3000');
});

Upvotes: 0

Views: 409

Answers (2)

hong4rc
hong4rc

Reputation: 4113

I think this code can help you:

console.log(JSON.stringify(req, null, 4));

Upvotes: 1

tonymke
tonymke

Reputation: 862

You can log the object itself to the console, and node will take care of this for you.

var http = require('http');

var server = http.createServer(function(req, res){
  console.log(req)
  res.end("Hi there \n");
});

server.listen(3000, function(){
    console.log('Server on 3000');
});

Gets you:

$ node script.js 
Server on 3000
IncomingMessage {
  _readableState: 
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     ...

Upvotes: 2

Related Questions