解析意外结束

时间:2016-02-26 01:59:09

标签: javascript node.js

有人可以解释一下我为什么会遇到这一行的问题,因为出于某种原因,当我在控制台中使用节点运行它时,我收到了Object.parse(本机)响应的意外输入结束。 / p>

var profile = JSON.parse(body);

完整代码:

//Problem: We need a simple way to look at a user's badge count and Javascript points
//Solution: Use Node.js to connect to Treehouse's API to get profile information to print out
var http = require("http");
var username = "testuser";

//Print out message
function printMessage(username, badgeCount, points) {
    var message = username + " has " + badgeCount + " total badge(s) and " + points + " points in Javascript";
    console.log(message);
}

//Print out error messages
function printError(error) {
    console.error(error.message);
}

//Connect to API URL (http://teamtreehouse.com/username.json)
var request = http.get("http://teamtreehouse.com/" + username + ".json", function(response) {
    var body = "";
    //Read the data
    response.on('data', function(chunk) {
        body += chunk;
    });
    response.on('end', function() {
        if(response.statusCode == 200){
            try {
                var profile = JSON.parse(body);
                printMessage(username, profile.badges.length, profile.points.Javascript);
            } catch(error) {
                //Parse Error
                printError(error);
            }
        } else {
            //Status Code Error
            printError({message: "There was an error getting the profile for " + username +".  (" + http.SSTATUS_CODES[response.statusCode] + ")"});
        }
    });
    //Parse the data
    //Print the data
});

//Connection Error
request.on('error', printError);

1 个答案:

答案 0 :(得分:0)

当我尝试浏览http://teamtreehouse.com/test.json时,它会将我重定向到相应的HTTPS网址。使用nodejs https模块并使用网址的https版本:https://teamtreehouse.com/test.json

或者使用可以处理重定向的热门请求模块和https:https://github.com/request/request。它也更容易使用。