Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set user agent for Node JS server

Is it possible to configure the user-agent of a simple Node JS server? For example, I would like to run my node server using an iPhone user agent to simulate the device display. Not sure if there is an NPM package doing this or a custom javascript to manipulate the user-agent of a Node JS server.

Detail: I am aware about express-user-agent

It will only give your parsing feature and access to your current user-agent within your Express app.

Here is the code of my Node JS server:

 var express = require('express');
 var app = express();
 var server = require('http').createServer(app);
 var io = require('socket.io')(server);
 var exec = require('child_process').exec;
 var shell = require('shelljs');

 app.use('/public', express.static(__dirname + '/public'));

 app.get('/', function(req, res,next) {
  res.sendFile(__dirname + '/index.html');
 });

 server.listen(4200);

 io.on('connection', function(client) {
  client.on('join', function(data) {
    console.log(data);
  });

 client.on('command', function(data) {
  console.log(data);
  });
 });
like image 203
Nizar B. Avatar asked Jan 16 '16 13:01

Nizar B.


People also ask

What is NodeJS HTTP agent?

The Agent manages connection persistence for HTTP clients. It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty. After that, the socket is destroyed, if the keepAlive is set to false .

What is my Useragent?

In simple words, it's a string of text that is unique for each software or browser on the internet and holds the technical information about your device and operating system. User-agent is present in the HTTP headers when the browser wants to connect with the webserver.


1 Answers

Look this:

var request = require('request');

var options = {
  url: 'http://localhost:4200/test',
  headers: {
    'User-Agent': 'MY IPHINE 7s'
  }
};

function callback(error, response, body) {
          //do somethings
}

request(options, callback);

For example you can add test-route to your server and send get request. Dont forget about url to request, it must be http://localhost:4200/test, code:

...

 app.use('/public', express.static(__dirname + '/public'));

 app.get('/', function(req, res,next) {
  res.sendFile(__dirname + '/index.html');
 });

app.get('/test', function(req, res,next) {
  console.log(req.headers);
});


server.listen(4200);

...
like image 51
siavolt Avatar answered Oct 06 '22 00:10

siavolt