开发者

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 r开发者_Go百科esolution, etc?

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

thanks!


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();
}


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


Have you read the API docs? The req object is a http.ServerRequest object as documented there. It's HTTP, and such things like resolution are not part of the protocol. What you can get is a user-agent, and from there you might be able to retrieve more information using another service.

Remember that node.js is a standalone app - it's not running in a browser - it's an HTTP Server application that is running in a JS interpreter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜