1

I'm trying to connect my node.js discord bot to my Rest API. I already look after some help on stackoverflow in this topic:

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

I'm stuck in the GET part of the function. The data I want is sent to the console but the bot don't receive it, while it receive hardcoded data.

Here is my code:

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);
    })
}

The data is well displayed in the console with the process.stdout.write(d); line, but doesn't appear in the bot response. I can get a hardcoded response with callback("response");, but not with callback(d)

It would be great if someone could help me a bit. thanks in advance

EDIT: Here are both the application log and the result on Discord enter image description here

Augustin Bocken
  • 379
  • 4
  • 18
Islena
  • 33
  • 4
  • Can you add both a capture of what the bot sends to your discord server and the data written in the console of the application ? – Augustin Bocken Oct 16 '18 at 08:19

1 Answers1

0

I got it working using this library : node-rest-client

You need to add those lines at the start of your file

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

Then, is used this code to make the call and use the callback

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

You have to change your file package.json to include the new library

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

For your next API calls, you can keep using

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){});

as long as you keep the good practice to reuse as much code as possible. For exemple, keeping the base of your url in one place and building your request's urls when you need them.

Augustin Bocken
  • 379
  • 4
  • 18