2

I'm trying to parse a JSON body from http.get. I know for a fact that the JSOn object is valid because I'm can eval successfully :

var json = document.body.innerText; 
obj = JSON.parse(json);

However, this code returns an error :

undefined:1
undefined{
Syntax error, Unexpected token u

My Node code :

function getCategories(callback){
    var body;
    var urlCats = "http://...";
    process.send(urlCats);
    http.get(urlCats, function(res){
        res.on('data', function (chunk) {
            body += chunk;
        });
        res.on('end', function () {
            callback(JSON.parse(body));
        });
    })
}

I have already seen Calling a JSON API with Node.js but I don't think it applies as I already get the body properly (callback(body) prints OK although the object starts with : undefined{). Any suggestions? Should I just cut the 'undefined' part of my body string? there must be something I'm missing! Thanks!

1 Answer 1

4

The problem is your


 var body;
 ...
 body += chunk;

body is declared but has the value 'undefined'.

therfor the first body += "something" translates into body = undefined + "something".

changing


 var body;

to


 var body = "";

should solve the problem.

Hope this helps,

Sign up to request clarification or add additional context in comments.

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.