0
votes

I am trying to pull some reddit posts from their json feed, as it is done in this example:

var http = require('http');


function getRedditPosts() {
  var url = "http://www.reddit.com/r/jokes/new/.json?limit=1";

  var request = http.get(url, function(response) {
    var json = '';
    response.on('data', function(chunk) {
      json += chunk;
    });

    response.on('end', function() {
      var redditResponse = JSON.parse(json);
      redditResponse.data.children.forEach(function(child) {
    if(child.data.domain !== 'self.node') {
      console.log('-------------------------------');
      console.log('Author : ' + child.data.author);
      console.log('Domain : ' + child.data.domain);
      console.log('Title : ' + child.data.title);
      console.log('URL : ' + child.data.url);
    }
      });
    })
  });
  request.on('error', function(err) {
    console.log(err);
  });
}

getRedditPosts();

The problem is that I am getting a unexpected end of JSON input. Why is that?

undefined:1

SyntaxError: Unexpected end of JSON input at Object.parse (native) at IncomingMessage. (/Users/felix/Desktop/Dev/npmTest/index.js:14:33) at emitNone (events.js:91:20) at IncomingMessage.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9)

1
There is a typo in your url `reddit.com/r/jokes/new.json?limit=1``Francois
@FrançoisP. Thanks, weird. Postman accepted this just fine.ffritz

1 Answers

1
votes

So, there is a typo in your url reddit.com/r/jokes/new.json?limit=1.

And you should use https instead of http package because reddit is https. Corrected code :

var http = require('https');


function getRedditPosts() {
  var url = "https://www.reddit.com/r/jokes/new.json?limit=1";

  var request = http.get(url, function(response) {
    var json = '';
    response.on('data', function(chunk) {
      json += chunk;
    });

    response.on('end', function() {
      var redditResponse = JSON.parse(json);
      redditResponse.data.children.forEach(function(child) {
    if(child.data.domain !== 'self.node') {
      console.log('-------------------------------');
      console.log('Author : ' + child.data.author);
      console.log('Domain : ' + child.data.domain);
      console.log('Title : ' + child.data.title);
      console.log('URL : ' + child.data.url);
    }
      });
    })
  });
  request.on('error', function(err) {
    console.log(err);
  });
}

getRedditPosts();