There was a problem with javascript’s JSON.parse

  node.js, question

Well, I want to try to use an api of hacker news, and then

var http = require('http');
 
 var hnApi =  'http://node-hnapi.herokuapp.com/news' ;
 
 var req = http.get(hnApi, function(res) {
 res.on('data', function(chunk) {
 console.log(chunk.toString());
 });
 });

There is no problem in this way. The result is really output at the terminal. However, I want to use JSON.parse to convert the string into an object, and there is a problem.

var http = require('http');
 var hnApi =  'http://node-hnapi.herokuapp.com/news' ;
 var news;
 
 var req = http.get(hnApi, function(res) {
 res.on('data', function(chunk) {
 console.log(chunk.toString());
 news = JSON.parse(chunk.toString());
 });
 });

It suggests that:

undefined:1
n”:”codepicnic.com”},{“id”:9747414,”title”:”A Sea Change in Treating Heart Att
SyntaxError: Unexpected end of input

Later I checked and found an answer like this:http://stackoverflow.com/questions/30942462/json-with-line-breaks-can- …

It was probably a line break, and then I tried again:

var http = require('http');
 var hnApi =  'http://node-hnapi.herokuapp.com/news' ;
 var news;
 
 var req = http.get(hnApi, function(res) {
 res.on('data', function(chunk) {
 console.log(chunk.toString());
 news = JSON.parse(chunk.toString().replace(/\n/g, ''));
 });
 });

However, it is still the same as the code above. Why is this?

I also encountered the same problem. data is a series of events. We have to splice the data together.

var body = '';
 res.on('data', function(chunk) {
 Body plus = chunk;
 ...
 });
 res.on('end',function(){
 console.log(body);
 ...
 });