How to get client information 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 information can I get from a client? like a browser, screen resolution, etc.?

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

thanks!

+7
javascript real-time
source share
3 answers

You cannot get screen resolution information, but you can get the user agent from the "User-Agent" request header

+5
source share

1) Referrer URL, IP address, User Agent, screen size and other statistics . You can also get a geographic location, but it is more active.

2) Some data is available in the headers, so it is sent for each request - other data, such as screen size, is a little more complicated, so you want to make an ajax request to send it.

 // 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(); } 
+16
source share

Have you read the docs API ? The req object is an http.ServerRequest object, as described there. This is HTTP, and things like permission are not part of the protocol. You can get a user agent, and from there you can get additional information using another service.

Remember that node.js is a standalone application - it does not work in the browser - it is an HTTP server application that runs in the JS interpreter.

+6
source share

All Articles