Thursday, 17 August 2017

proxy for nodejs application

If you are in a corp environment. most of companies will need to use proxy to access internet.

If you use Nodejs, NPM can setup proxy globally, but you cannot set a global proxy for your application.


I did a log of research, i found different solutions: (if your corp proxy request username and password to login, then please go to the end of this post)


you can try

1. global tunnel,  which is here:  https://www.npmjs.com/package/global-tunnel. However, this is very basic proxy, it doesn't accept username and password.  but this is a kind of global proxy, this will apply this proxy to all http requests.

2. tunnel,  which is here https://www.npmjs.com/package/tunnel .  this is better, but does not support username and password neither. this is not global, you need to put this proxy into each http request.

3. http, you also can do this directly to http:

var http = require("http");

var options = {
  host: "proxy",
  port: 8080,
  path: "http://www.google.com",
  headers: {
    Host: "www.google.com"
  }
};
http.get(options, function(res) {
  console.log(res);
  res.pipe(process.stdout);
});
or :
http://geekswithblogs.net/shaunxu/archive/2013/09/05/semi-global-proxy-setting-for-node.js.aspx



4. request with proxy:

var request = require('request');
request({'url':'https://anysite.you.want/sub/sub',
        'proxy':'http://yourproxy:8087'}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
})

this solution support proxy auth.

var request = require('request');
request({'url':'https://anysite.you.want/sub/sub',
        'proxy':'http://domain\yourusername:yourpassword@yourproxy:8087'}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
})

note: "domain\yourusername:yourpassword" this need to be url encoded. you can use this to encode it:

https://meyerweb.com/eric/tools/dencoder/






No comments:

Post a comment