How can I use and allow http proxy with node.js http.Client

I am sending an HTTP request through a proxy to add username and password to my request. How do I correctly add these values ​​to my option block?

This is my code:

var http = require('http');

var options = {
  port: 8080,
  host: 'my.proxy.net',
  path: '/index',
  headers: {
   Host: "http://example.com"
  }
};


http.get(options, function(res) {
  console.log("StatusCode: " + res.statusCode + " Message: " + res.statusMessage);
});

      

Currently the answer is StatusCode: 307, Message: Authentication Required .

I tried to add username and password to my options, but it doesn't work:

var options = {
    port: 8080,
    host: 'my.proxy.net',
    username: 'myusername',
    password: 'mypassword',
    path: '/index',
    headers: {
       Host: "http://example.com"
    }
};

      

Additional information: I have little information about proxies, but otherwise this authentication method worked:

npm config set proxy http://username:password@my.proxy.net:8080

      

+3


source to share


1 answer


Ok, this works with my local squid:

var http = require('http');

function buildAuthHeader(user, pass) {
    return 'Basic ' + new Buffer(user + ':' + pass).toString('base64');
}

proxy = 'localhost';
proxy_port = 3128;
host = 'www.example.com';
url = 'http://www.example.com/index.html';
user = 'potato';
pass = 'potato';

var options = {
    port: proxy_port,
    host: proxy,
    path: url,
    headers: {
        Host: host,
       'Proxy-Authorization': buildAuthHeader(user, pass),
    }
};

http.get(options, function(res) {
  console.log("StatusCode: " + res.statusCode + " Message: " + res.statusMessage);
});

      



Couple notes:

  • The full url needs to be included in the GET string, not just the path, so its not /index.html but http://example.com/index.html
  • You must also include the host in the host header, so you will need to parse the url correctly
+2


source







All Articles