如何将带有 Node.js 的 http(s) 请求发送到由 LocalTunnel 托管的 Node.js 服务器

How to send http(s) requests with Node.js to a Node.js server hosted with LocalTunnel

我有一个非常基本的 node.js 服务器:

var http = require("http");

var server = http.createServer(function(req, res){
    console.log("Got request");

    res.writeHead(200, {"Content-Type":"text/plain"});
    res.end("Hi there!");
});

server.listen(3004);

我可以通过我的浏览器并通过从 Node.js 客户端发送请求来访问它:

var http = require("http");

var options = {
    "hostname": "localhost",
    "port": 3004,
    "path": "/",
    "method": "GET"
};

var req = http.request(options, function(res){
    var data = "";

    res.on("data", function(chunk){
        data += chunk;
    });

    res.on("end", function(){
        console.log(data);
    });
});

req.on("error", function(e){
    console.log(e.stack);
});

req.end();

现在,如果我将 localtunnel 包用于 "host" 此服务器 ( lt --port 3004 ),我现在将获得我的新主机名,我应该能够从 Internet 上访问它。事实上,我可以从浏览器轻松访问它。

但是,如果我尝试使用新的主机名从 Node.js 客户端发送 https(不是 http,因为 lt 使用 https)请求,请求被拒绝并且我收到此错误:

Error: connect ECONNREFUSED 138.197.63.247:3004 at TCPConnectWrap.afterConnect [as oncomplete]

那么当 node.js Web 服务器由 localtunnel 托管时,是否无法访问它?或者如果有(可能使用第三部分模块)有人可以指导我如何完成,因为 google 绝对没有帮助。提前致谢。

EDIT1:我应该注意,在服务器端,错误消息确实建议“检查我的防火墙,但我不知道我的防火墙中有什么可以阻止它,我不确定该怎么做。(请记住,这在从浏览器连接时有效??)

EDIT2:顺便说一句,我试图完全删除我的防火墙(得到相同的结果)

您需要在服务器代码中使用 Node.js 的 HTTPS 模块才能通过 HTTPS 协议访问它。创建 HTTPS 服务器需要证书和密码。

来自文档:

const https = require('https');
const fs = require('fs');

const options = {
  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
  passphrase: 'sample'
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000);

问题是您没有使用正确的端口发送请求。当您使用像 localtunnel 这样的隧道服务时,它会将您的服务器托管为 HTTPS。现在通常用于 HTTPS 的端口是 443 端口,所以选项对象应该是这样的:

var options = {
    "hostname": "whatever",
    "port": 443,  //HERE!
    "path": "/",
    "method": "GET"
};

zeitheroku 从他们的云托管您的应用程序的服务也是如此。

Telebit 是一项类似的服务,尽管目标略有不同,但我相信它会支持您的用例。

HTTPS (tls/ssl) 由 Greenlock.js 和 Let's Encrypt 支持,因此您无需修改​​节点服务器或手动配置任何内容 - 端到端加密自动处理。

安装

curl https://get.telebit.io | bash

您也可以通过 npm 安装...但这不是目前首选的安装方法。可能有一些注意事项。

您获得的随机域已附加到您的帐户(因此需要电子邮件)。

配置

./telebit http 4000

一般格式为

./telebit <protocol> <port> [subdomain]

它不仅是 https,您还可以使用它通过 tls/ssl(纯 tcp、ssh、openvpn 等)隧道 任何东西

自定义域还不是普遍可用的功能,但即将推出。