node.js和json运行时错误
我正在使用node.js并试图parsing请求的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)
我在做:
request.on('data', function(chunk) { data+=chunk; }); // and in the end I am doing obj = JSON.parse(data); // it's complaining at this point.
input是:
{ "result": "success", "source": "chat" }
你试图在数据完全收到之前parsing数据…把你的JSON.parse放入请求的.end方法
var data = ''; request.on('data', function(chunk){ data += chunk; }); request.on('end', function(){ var obj = JSON.parse(data); });
随着你的编辑:在你的代码中你在做JSON.parse? 请记住request.on是asynchronous的; 你不能调用JSON.parse
直到数据完成( request.on('end')
)…如果你只是在下一个调用它,那么你可能在数据到达之前调用它。
例如
request.on('data', function(chunk) { data+=chunk; }); request.on('end', function() { obj = JSON.parse(data); });
会工作,但是
request.on('data', function(chunk) { data+=chunk; }); obj = JSON.parse(data);
将不会,因为JSON.parse可能会在任何'data'
callback触发之前被调用。
“意外的input结束”是您尝试parsing空string或不完整的JSONstring时得到的错误消息:
// examples JSON.parse('') JSON.parse('{')
所以这听起来像你的数据源是不可靠的。 处理这个问题的正确方法是在JSON.parse()步骤失败时返回400范围的响应给客户端。
function connectionHandler(request, response) { var data = ''; request.on('data', function(buffer) { data += buffer; }); request.on('end', function() { response.writeHead(200, { 'Content-Type': 'application/json' }); try { data = JSON.parse(data.toString()); } catch (e) { response.end(); return; } if (!data) { return; } // process "data" here }) }