是这样的,我想尝试使用一个hacker news 的 api,然后
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());
});
});
这样是没有问题的,真的在终端输出结果了,但是,我想用 JSON.parse 把那个字符串转成对象,就出问题了
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());
});
});
它提示:
undefined:1
n":"codepicnic.com"},{"id":9747414,"title":"A Sea Change in Treating Heart Att
SyntaxError: Unexpected end of input
后来我查了一下,找到了类似这样的答案: http://stackoverflow.com/questions/30942462/json-with-line-breaks-can-...
大概是换行符的问题,然后我再次尝试:
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, ''));
});
});
但是还是同样的跟上面的那段代码一样报错,这是为什么呢?
认证高级PHP讲师