【问题标题】:Error when using JSON.parse in node.js在 node.js 中使用 JSON.parse 时出错
【发布时间】:2012-11-20 13:23:47
【问题描述】:

我正在编写一个简单的程序,该程序向 reddit 发出请求,并以 JSON 格式返回页面。我通过将“.json”附加到 reddit url 的末尾来做到这一点。例如,如果我想获取我的个人资料页面,我会执行“www.reddit.com/user/stebon24.json”。

到目前为止,这是我的程序。我将在下面记录并描述错误。

var http = require('http');
var options = {
    host: 'www.reddit.com',
    path: ''
};

module.exports = function(username) {

    console.log(username);

    options.path = '/user/' + username + '.json';

    var userData;

    http.get(options, function(res) { 

        res.on('data', function(data) {
            userData += data;
            console.log(userData);
        });

        res.on('end', function() {
            userData = JSON.parse(userData);
            console.log(userData);
        });
    });
};

至于错误,它发生在程序到达需要运行 JSON.parse() 的位置时。我知道这一点,因为当我在“数据”事件上记录结果时,我可以看到它输出原始 JSON。然后输出这个错误...

undefined:1
undefined{"kind": "Listing", "data": {"modhash": "", "children": [{"kind": "t1
^
SyntaxError: Unexpected token u
    at Object.parse (native)
    at IncomingMessage.module.exports (/home/stephen/Desktop/karmacrawler/engine/crawlUser.js:23:20)
    at IncomingMessage.EventEmitter.emit (events.js:126:20)
    at IncomingMessage._emitEnd (http.js:366:10)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
    at Socket.socketOnData [as ondata] (http.js:1367:20)
    at TCP.onread (net.js:403:27)

【问题讨论】:

    标签: json node.js parsing


    【解决方案1】:

    记得为userData设置一个初始值,这样它就不会被初始化为“未定义”:

    var userData = '';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-31
      • 2018-01-28
      • 2013-02-02
      • 1970-01-01
      • 2013-02-18
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多