【问题标题】:Node js bind request to different interface or IP addressNode js将请求绑定到不同的接口或IP地址
【发布时间】:2016-12-17 08:29:02
【问题描述】:

我想强制我的 node js 应用通过特定的接口或 IP 地址下载。

在带有 wget 的 Linux 中,我可以通过以下方式做到这一点:

wget --bind-address=192.168.21.21 http://example.com

或与 curl 类似:

curl --interface 192.168.21.21 --ipv4 http://example.com

我目前正在使用request 包,但我看不到类似的选项,如果需要的话可以更改。

如何将我的下载绑定到 IP 地址或与节点 js 请求的接口?

编辑:我在 cmets 中看到了这些问题,但它们似乎没有解决我如何在请求中执行此操作的问题,而且我没有使用 expressjs,因为我的应用程序没有服务器/网络存在。

【问题讨论】:

标签: node.js bind ip-address


【解决方案1】:

我也有同样的要求,但事实证明这很容易做到。只需在request 中使用localAddress 选项(与http 模块中的选项相同):

(async () => {

  let request = require('request-promise-native'); // (a promisified version of request module)

  // This prints your machine's IP
  console.log( await request({ uri: 'https://api.ipify.org' }) );

  // This prints '***.***.***.***'
  console.log( await request({ uri: 'https://api.ipify.org', localAddress: '***.***.***.***' }) );

})();

(用您的新静态 IP 替换 ***.***.***.***

请注意,您当然需要已设置静态 IP 并已在您的操作系统中配置它。如果它对任何人有帮助,使用 Ubuntu 16.04,您只需将其添加到 /etc/network/interfaces 文件的末尾即可:

auto ens3:0
iface ens3:0 inet static
  address ***.***.***.***
  netmask 255.255.254.0

(同样,将***.***.***.*** 替换为您的IP)更多详细信息here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    相关资源
    最近更新 更多