Node js将请求绑定到不同的接口或IP地址

Node js bind request to different interface or IP address

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

在 Linux 和 wget 中,我可以用这样的方法来做到这一点:

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

或与 curl 类似:

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

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

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

编辑:我在评论中看到了问题,但它们似乎没有解决我的问题,即如何根据请求执行此操作,而且我没有使用 expressjs,因为我的应用程序没有 server/web 存在感。

我也有同样的要求,事实证明这很容易做到。只需使用 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 并在 OS 中进行配置。如果它对任何人有帮助,使用 Ubuntu 16.04,您只需将其添加到 /etc/network/interfaces 文件的末尾:

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

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