Node.js 调用 Rest 时 Discord 机器人消息为空 API

Node.js Discord bot message empty when calling the Rest API

我正在尝试将我的 node.js discord 机器人连接到我的 Rest API。我已经在这个主题中寻找了一些关于 Whosebug 的帮助:

How to make remote REST call inside Node.js? any CURL?

我卡在了函数的 GET 部分。我想要的数据已发送到控制台,但机器人没有接收到它,而它接收的是硬编码数据。

这是我的代码:

function execute_testrest(callback) {

    var options = {
            host : 'localhost',
            port : '55978',
            path : '/api/values',
            method : 'GET'
    };

    console.info('Options prepared:');
    console.info(options);
    console.info('Do the GET call');

    var reqGet = http.request(options, function(res) {
        console.log("statusCode: ", res.statusCode);
        console.log("headers: ", res.headers);

        res.on('data', function(d) {
            console.info('GET result:\n');
            process.stdout.write(d);   
            callback(d);
            console.info('\n\nCall Completed');
        });
    });

    reqGet.end();
    reqGet.on('error', function(e) {
        console.error(e);
    })
}

数据通过 process.stdout.write(d); 行很好地显示在控制台中,但没有出现在机器人响应中。 我可以使用 callback("response"); 获得硬编码响应,但不能使用 callback(d)

如果有人能帮我一点忙就好了。 提前致谢

编辑:这是应用程序日志和 Discord 上的结果

我使用这个库让它工作:node-rest-client

您需要在文件开头添加这些行

var Client = require('node-rest-client').Client;
var client = new Client();

然后,使用此代码进行调用并使用回调

var url = "http://localhost:49952/api/values";
client.get(url,function(data,response){
    console.log(data);
    console.log(response);
    callback(data);
});

您必须更改文件 package.json 以包含新库

"node-rest-client": "^3.1.0"

下次 API 次通话,您可以继续使用

client.get(url, function(data,response){});
client.post(url, args, function(data,response){});
client.put(url, args, function(data,response){});
client.delete(url, function(data,response){});

只要您保持重复使用尽可能多的代码的良好做法。例如,将 url 的基础放在一个地方,并在需要时构建请求的 url。