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

查看:51
本文介绍了如何在 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?

推荐答案

蒂姆·麦克法兰="https://stackoverflow.com/questions/3862813/how-can-i-use-an-http-proxy-with-node-js-http-client/5810547#5810547">answer 已关闭关于使用 HTTP 代理.

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

使用 HTTP 代理(用于非安全请求)非常简单.您连接到代理并正常发出请求,只是路径部分包含完整的 url 并且主机标头设置为您要连接的主机.
蒂姆非常接近他的答案,但他错过了正确设置主机标头.

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天全站免登陆