如何通过 node.js http.Client 使用和授权 http 代理

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

我正在通过代理发送一个 http 请求,需要在我的请求中添加用户名和密码。如何正确地将这些值添加到我的选项块中?

这是我的代码:

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

当前响应是 状态代码:307,消息:需要身份验证

我尝试将用户名和密码添加到我的选项中,但它不起作用:

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

附加信息: 我没有太多关于代理的信息,但在另一种情况下,这种身份验证方法有效:

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

好的,这适用于我当地的鱿鱼:

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

夫妇注意事项:

  1. 完整的 URL 必须包含在 GET 行中,而不仅仅是路径,所以它不是 /index.html 而是 http://example.com/index.html
  2. 您还应该在主机 header 中包含主机,因此您必须正确解析 URL