如何在 Node.js 服务器中发出 HTTP/HTTPS 请求?

How to make an HTTP/HTTPS request within a Node.js server?

我刚刚开始学习 Node.js,现在,我正在尝试通过 cPanel 使用 Node.js 应用程序,以便在应用程序 [=] 时提供 JSON 响应37=] 被访问。

访问应用程序的 URL 时,很明显 Node.js 服务器正在正常工作。所以在编辑主 JS 文件并重新启动 Node.js 应用程序后,更改会在再次访问 URL 时反映出来。

我的问题: 在 https.createServer( function (req, res) {}); 的功能中,我想向其他地方的 PHP 文件发出一个 HTTPS 请求,returns 一个 JSON 响应。目前,我什至无法从使用 PHP 文件的任何类型的请求中获得响应或错误。

var https = require('https');
var server = https.createServer(function (req, res) {
    var message = "";
    res.writeHead(200, {
        'Content-Type': 'text/plain'
    });

    var options = {
        host: "mydomain.com",
        path: '/myPhpScript.php'
    };
    https.get(options, function(res) {
        var bodyChunks = [];
        res.on('data', function(chunk) {
            bodyChunks.push(chunk);
        }).on('end', function() {
            var body = Buffer.concat(bodyChunks);
            message += body;
        })
    }).on('error', function(e) {
        message += e;
    });
    res.end(message);
});
server.listen();

如您所见,message 将显示给浏览器 window,但它是空的。访问应用程序时没有任何显示 URL。是否可以使用 Node.js HTTPS 服务器发出 HTTPS 请求?

注意: 我也尝试过 native-requestaxios 并且遇到了同样的问题。

服务器代码:

var http = require('http');
var https = require("https");

var server = http.createServer(function (req, res) {

    let call = new Promise((resolve, reject) => {

        var options = {
            host: "jarrenmorris.com",
            port: 443,
            path: '/gamesense/r6_db/1.json'
        };

        https.get(options, function (res) {

            var bodyChunks = [];

            res.on('data', function (chunk) {
                bodyChunks.push(chunk);
            }).on('end', function () {
                resolve(Buffer.concat(bodyChunks));
            });

        }).on('error', function (e) {
            reject(e);
        });

    });


    call.then((data) => {

        // do something here with the successful request/json

        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });

        res.end(data);

    }).catch((err) => {

        // do something here with the failure request/json
        // res.write("ERROR:");
        res.end(err);

    });

});

server.listen(8081, "127.0.0.1", () => {
    console.log(`Server listen on ${server.address().address}:${server.address().port} `);
});

回复:

{"name":"tim","age":"42"}

我注意到的第一件事是,当我尝试 运行 您的代码时,您无法与您的 node.js 建立连接。

这是因为您使用了 https 模块,但没有指定 certificates/keyfiles。跳过这个,并使用 http 直到你得到你想要的结果。

然后我将您的 https 请求打包到一个承诺中 api/file。 这允许简单的链接和更好的代码可读性。

当承诺 resolves/fullfill 时,我们使用从外部请求收到的数据在 http 服务器上响应请求。

代码中的 res.end(放置的位置)没有意义,因为您没有等待外部请求完成。这就是为什么在浏览器中没有显示任何内容的原因 window。