解析意外的结局

问题描述:

有人可以请解释我为什么我得到这一行的问题,因为由于某种原因,当我在控制台中运行它与节点我收到意外的输入在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://*.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

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

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