2016-02-26 61 views
-2

有人可以請解釋我爲什麼我得到這一行的問題,因爲由於某種原因,當我在控制檯中運行它與節點我收到意外的輸入在Object.parse(本機)響應。解析意外的結局

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); 
+0

可能重複的[SyntaxError:在Object.parse(本機)npm請求輸入意外結束](http://stackoverflow.com/questions/29259395/syntaxerror-unexpected-end-of-input-at-object- parse-native-npm-request) –

+0

查看我的編輯,因爲我沒有看到我的問題。 – user3732216

+1

您是否檢查過請求中的JSON?它有效的JSON?嘗試使用瀏覽器的開發工具在響應中複製JSON,然後使用JSON linter /驗證器驗證它。 'JSON.parse()'非常挑剔。 – kevin628

回答