node.js和json运行时错误

The*_*ner 12 json node.js

我正在使用node.js并尝试解析请求的JSON主体.我收到以下错误:

undefined:0

^
SyntaxError: Unexpected end of input
    at Object.parse (native)
    at IncomingMessage.<anonymous> (C:\node\xxxx.js:36:14)
    at IncomingMessage.emit (events.js:64:17)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:130:23)
    at Socket.ondata (http.js:1506:22)
    at TCP.onread (net.js:374:27)
Run Code Online (Sandbox Code Playgroud)

我在做:

     request.on('data', function(chunk)
    {
    data+=chunk;
    });
     // and in the end I am doing
     obj = JSON.parse(data);  // it's complaining at this point.
Run Code Online (Sandbox Code Playgroud)

输入是:

{
    "result": "success",
    "source": "chat"
}
Run Code Online (Sandbox Code Playgroud)

Pas*_*nes 29

您正在尝试在完全收到数据之前解析数据...将您的JSON.parse放在.end请求方法中

var data = '';
request.on('data', function(chunk){
  data += chunk;
});
request.on('end', function(){
  var obj = JSON.parse(data);
});
Run Code Online (Sandbox Code Playgroud)