简体   繁体   中英

node http.get parse JSON body

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!

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM