0

Been trying to solve this problem for a while now. I'm aware there are similar problems on stack overflow, but none of the solutions are working for me and I need some help. I'm getting the error message

undefined:1



SyntaxError: Unexpected end of JSON input
    at Object.parse (native)
    at IncomingMessage.<anonymous> (B:\-\memeFinder.js:27:20)
    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)

When running this code:

var http = require('http');

getRedditMemes();

function getRedditMemes () {
    var options = {
        host: 'www.reddit.com'
        path: '/r/me_irl/hot/.json?count=20'
        headers: {'User-agent':'xxxxx', 'Accept-Charset':'UTF-8'}
    };

    http.get(options, function (response) {
        var str = '';

        response.on('data', function (chunk) {
            console.log(chunk)
            str += chunk;
        })

        response.on('end', function () {
            console.log(str);
            var root = JSON.parse(str); //This line is where I'm getting the error
        })
    }).end();
}

I'm aware that there are other answers here that explain that the error is a result of incomplete json, but most of the applicable answers say to place the parsing code in response.on('end') which I'm already doing. It's probably some stupid small thing, but help is much appreciated, thanks.

Edit: Thanks for the responses everyone. I appreciate the quick help.

1
  • Did you check your Network panel and confirmed your http call returns data? Commented Jan 17, 2017 at 6:15

2 Answers 2

1

The request is returning a 301 (redirect) error, and the http package isn't following it. You can either build logic in to follow the redirect, or use a wrapper like follow-redirects:

Change your first line to:

var http = require('follow-redirects').http;
Sign up to request clarification or add additional context in comments.

Comments

0

Simply put, The variable str is not a valid JSON object string. try console logging the variable chunk and see. Chances are chunk is undefined or null.

1 Comment

Yeah, when I throw a console log on the chunk it doesn't show any output in the console. I forgot to include that in the original post. What might fix that problem though? I'm not controlling what the callback is called with so I'm a little lost.

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.