Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get information about the client in node.js

in this very simple example:

var sys = require("sys"),
    http = require("http");

http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end("Hello World!");
}).listen(8080);

sys.puts("Server running at http://localhost:8080/");

1.) What kind of information can I get from the client? like browser, screen resolution, etc?

2.) How can I send information from the client to server, like parameter?

thanks!

like image 726
oscarm Avatar asked Oct 09 '10 02:10

oscarm


2 Answers

1) Referrer URL, IP address, User Agent, screen size and other stats. You can also get geo location but that is more involved.

2) Some data is available in the headers so these are sent on every request - other data such as screen size is a little trickier so you'll want to make an ajax request to send that along.

// Somewhere on your page(s) - here we use jQuery
$(document).ready(function(){   
  // Check if they have been logged
  if ($.cookie('logged') == null ){
    // Send screen size and whatever else that is not available from headers
    $.post('/logger', { width: screen.width, height: screen.height }, function(res) {
      // Set cookie  for 30 days so we don't keep doing this
       $.cookie('logged', true, { expires: 30 }); 
    });
  } 
 });  

// Server side - example is an Express controller
exports.logger = function(req, res) {
  var user = {
    agent: req.header('user-agent'(, // User Agent we get from headers
    referrer: req.header('referrer'), //  Likewise for referrer
    ip: req.header('x-forwarded-for') || req.connection.remoteAddress, // Get IP - allow for proxy
    screen: { // Get screen info that we passed in url post data
      width: req.param('width'),
      height: req.param('height')
    }
  };
  // Store the user in your database
  // User.create(user)...
  res.end();
}
like image 79
cyberwombat Avatar answered Oct 29 '22 02:10

cyberwombat


You can't get the screen resolution information, but you can get the user agent from Request Header "User-Agent"

like image 30
leeight Avatar answered Oct 29 '22 01:10

leeight