node.js和json运行时错误 [英] node.js and json runtime error

查看:84
本文介绍了node.js和json运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using node.js and trying to parse the JSON body of a request. I am getting the following error:

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)

我正在做

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

输入为:

{
    "result": "success",
    "source": "chat"
}

推荐答案

您正在尝试完全解析数据之前……将JSON.parse放入request的.end方法内

You're trying to parse the data before it is completely recieved...put your JSON.parse inside the .end method of request

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

这篇关于node.js和json运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆