HTTP请求的响应无法从字符串转换为JSON

时间:2014-11-17 23:11:29

标签: json http

这是http.request的功能,如下所示:

var post_req =http.request(options,function(res){
    console.log('STATUS:'+res.statusCode);
    console.log('HEADERS: '+JSON.stringify(res.headers));
    var str ='';
    res.setEncoding('utf8');
    res.on('data',function (chunk){
        str += chunk;

    });
    res.on('end',function(){
        console.log("message="+str);
    });
    res.on('error',function(e){

    });
    var token= JSON.parse(str);
    console.log(token);

这是我从控制台得到的错误,有人能告诉我我的代码有什么问题吗?

undefined:0

^
SyntaxError: Unexpected end of input
    at Object.parse (native)
    at ClientRequest.<anonymous> (/Users/guojiaqi/Documents/workspace/ejs/APIintegration.js:27:18)
    at ClientRequest.g (events.js:180:16)
    at ClientRequest.emit (events.js:95:17)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (http.js:1692:21)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
    at CleartextStream.socketOnData [as ondata] (http.js:1587:20)
    at CleartextStream.read [as _read] (tls.js:513:12)
    at CleartextStream.Readable.read (_stream_readable.js:340:10)
    at EncryptedStream.write [as _write] (tls.js:368:25)

1 个答案:

答案 0 :(得分:1)

您的str变量为空,因为您正在使用事件处理程序从网络流中读取数据,但是当您开始使用str进行操作时,您不会等待它们完成。将JSON.parse(str)移到res.on('end', ...)内,以便在完成下载后解析JSON。