如何在node.js http.Client中使用http代理? [英] How can I use an http proxy with node.js http.Client?

查看:143
本文介绍了如何在node.js http.Client中使用http代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用标准的 http.Client 从node.js发出传出的HTTP调用。但我无法直接从我的网络到达远程服务器,需要通过代理。

I want to make an outgoing HTTP call from node.js, using the standard http.Client. But I cannot reach the remote server directly from my network and need to go through a proxy.

如何告诉node.js使用代理?

How do I tell node.js to use the proxy?

推荐答案

Tim Macfarlane 答案关于使用HTTP代理已经接近。

Tim Macfarlane's answer was close with regards to using a HTTP proxy.

使用HTTP代理(非安全请求)非常简单。您连接到代理并正常发出请求,除了路径部分包含完整的URL并且主机头设置为您要连接的主机。

Tim非常接近他的答案但是他错过了正确设置主机头。

Using a HTTP proxy (for non secure requests) is very simple. You connect to the proxy and make the request normally except that the path part includes the full url and the host header is set to the host you want to connect to.
Tim was very close with his answer but he missed setting the host header properly.

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

对于记录,他的回答适用于 http://nodejs.org/ 但这是因为他们的服务器并不关心主机头是不正确的。

For the record his answer does work with http://nodejs.org/ but that's because their server doesn't care the host header is incorrect.

这篇关于如何在node.js http.Client中使用http代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆