javascript Node.js undefined:1 [SyntaxError: Unexpected end of input]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28233505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:38:13  来源:igfitidea点击:

Node.js undefined:1 [SyntaxError: Unexpected end of input]

javascriptjsonnode.jsgoogle-api-nodejs-client

提问by Mahavir Munot

I am getting the following error when I execute the node.js script, I tried to investigate a lot by adding console.log() to trace the error but could not find any solution. [Note: I have also searched other Stackoverflow solution but none of it helped]

执行 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)

Here is my code:

这是我的代码:

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();

When I call the api using curl command, I get the below valid json response:

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

{"ydht":{"status":{"code":200,"message":"OK"},"records":[{"metadata":{"seq_id":"intusnw1-14B3579A577-3","modtime":1422531339,"disk_size":99},"key":"[email protected]","fields":{"em":{"value":"[email protected]"},"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"}}}

回答by Ben Fortune

The datacallback is called multiple times with chunks of the response. On each callback you need to append the response to a string and then on end, that's when you parse it.

使用data响应块多次调用回调。在每个回调中,您需要将响应附加到一个字符串然后 on 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);
        }
    });
});

回答by rezwits

For me when I get this error:

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

undefined:1
[

It's because the .json file is saved as:

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

8-bit unicode BOM, Win (CRLF) instead of: 8-bit unicode, Win (CRLF)

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

it needs to be the later for me!

对我来说应该是后者!

LATE

晚了

回答by Codemator

First of all Thank you Ben for the correct root cause analysis. I have tried the solution Ben proposed, but since my response data was so huge, it started giving me "socket hang up" error. So I have to redesign the solution using node.js request module

首先感谢 Ben 进行正确的根本原因分析。我已经尝试了 Ben 提出的解决方案,但由于我的响应数据非常庞大,它开始给我“套接字挂断”错误。所以我必须使用 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

});