0

I'm working on a small discord bot which requires me to do some JavaScript. I know there is some alternatives but I want to use JavaScript because of reasons. The thing is I'm trying to make a get request for JSON in node.js but It only seems to work if I put the data (chunk) into the console. If I try to concat the data I just get an empty string.

Here is my code:

var https = require('https');
var output;

var options = {
    host: '---',
    port: 443,
    method: 'GET',
   // json: true,
    path: '/post/index.json?limit=15',
    headers: { 'user-agent': 'DiscordLucario/1.0' }
};

var req = https.request(options, function (res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        //console.log(chunk);
        output += chunk;
    });
});
req.on('error', function (e) {
    console.log('problem with request: ' + e.message);
});
req.on('end', function () {

    console.log(output);
    GTwebObject = JSON.parse(output);
    GTpictureIndex = getRandomInt(1, GTwebObject.length);
    GTpictureTags = GTwebObject[GTpictureIndex].tags;
    GTpictureURL = GTwebObject[GTpictureIndex].file_url;

});
req.end();
0

2 Answers 2

1

I believe that chunk is a buffer so you need to convert it to a string before concatenating.

res.on('data', function (chunk) {
    //console.log(chunk);
    output += chunk.toString();
});
Sign up to request clarification or add additional context in comments.

2 Comments

I think better advice might be to use npmjs.com/package/request rather than dealing with node's http/https interfaces directly anyway.
Thanks to you both. But it didnt change anything sadly. But I will keep the change.
0

Try converting the chunk data stream to String before concat.

var textChunk = chunk.toString('utf8');
output += textChunk

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.