Node.js undefined:1 [SyntaxError:意外的输入结束]

时间:2015-01-30 10:10:11

标签: javascript json node.js google-api-nodejs-client

当我执行node.js脚本时出现以下错误,我尝试通过添加console.log()来跟踪错误但无法找到任何解决方案。 [注意:我也搜索了其他Stackoverflow解决方案,但没有一个帮助]

undefined:1
   {"ydht":{"status":{"code":200,"message":"OK"},"records":[
                                                     ^
SyntaxError: Unexpected end of input
at Object.parse (native)
at IncomingMessage.<anonymous> (/tmp/subs_20140130/inc/getData.js:36:24)
at IncomingMessage.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (_stream_readable.js:745:14)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:407:10)
at emitReadable (_stream_readable.js:403:5)
at readableAddChunk (_stream_readable.js:165:9)
at IncomingMessage.Readable.push (_stream_readable.js:127:10)
at HTTPParser.parserOnBody [as onBody] (http.js:142:22)

这是我的代码:

var options = {
  host: '<my host>',
  port: 3128,
  path: 'http://<some host>:4080'+searchQuery,
  method: 'GET',
  headers: {
     'App-Auth': cert
  }
};
var req = http.request(options, function(res) {   
  res.setEncoding('utf8'); //DEBUG
  for ( var k in options) { console.log("[LOGGING] options :" + k + " = " + options[k]);} //DEBUG
  res.on('data', function (resData) {
    var resObj = "";
    resObj =  JSON.parse(resData);
    console.log("[LOGGING] Response:: "+resObj);               
    if(resObj.ydht.status.code === 200 && resObj.ydht.records[0].key.length > 0) {
      console.log("[LOGGING] Email   "+em+"  Key       "+resObj.ydht.records[0].key);          
      var filePath = basePath + '/setData';
      var setd = require(filePath);
      setd.setMagData(resObj.ydht.records[0].key, ycacert, is_sub);
    } else {
      console.log("[LOGGING] Fail to fetch data em        "+em+"  nl      "+nl);
    }
  });
  res.on('end', function() {
    console.log("[LOGGING] connection closed");
  });
});
req.on('error', function(err) {
  console.log("[LOGGING] Fail to fetch data em        "+em+"  nl      "+nl);
});
req.end();

当我使用curl命令调用api时,我得到以下有效的json响应:

{"ydht":{"status":{"code":200,"message":"OK"},"records":[{"metadata":{"seq_id":"intusnw1-14B3579A577-3","modtime":1422531339,"disk_size":99},"key":"201408271148_zy@gmail.com","fields":{"em":{"value":"xyz1408@yahoo.in"},"is_confirm":{"value":""},"nl":{"value":"offerpop1"}}}],"continuation":{"scan_completed":false,"scan_status":200,"uri_path":"/YDHTWebService/V1/ordered_scan/dts.subs_email?order=asc&start_key=a0"}}}

3 个答案:

答案 0 :(得分:16)

使用响应块多次调用data回调。在每个回调中,您需要将响应附加到字符串,然后在end上,就在您解析它时。

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    var body = "";
    res.on('data', function(resData) {
        body += resData;
    });
    res.on('end', function() {
        var json = JSON.parse(body);
        if (json.ydht.status.code === 200 && json.ydht.records[0].key.length > 0) {
            var filePath = basePath + '/setData';
            var setd = require(filePath);
            setd.setMagData(json.ydht.records[0].key, ycacert, is_sub);
        } else {
            console.log("[LOGGING] Fail to fetch data em        " + em + "  nl      " + nl);
        }
    });
});

答案 1 :(得分:1)

当我收到此错误时,对我来说:

undefined:1
[

这是因为.json文件保存为:

8位unicode BOM,Win(CRLF) 代替: 8位unicode,Win(CRLF)

它必须是我的后期!

LATE

答案 2 :(得分:0)

首先,感谢Ben对正确的根本原因进行分析。我已经尝试过Ben提出的解决方案,但由于我的响应数据非常庞大,它开始让我&#34; socket挂断&#34;错误。所以我必须使用node.js请求模块重新设计解决方案

//Load the request module ( Dont forget to include it in package.json dependency "request": "2.x.x")
var request = require('request');

request('http://xys.com/api', function (error, response, body) {
    //Check for error
    if(error){
        return console.log('Error:', error);
    }

    //Check for right status code
    if(response.statusCode !== 200){
        return console.log('Invalid Status Code Returned:', response.statusCode);
    }

    console.log(body); // Here is the response body

});