NodeJS请求响应偶尔会出现“解析错误”消息

时间:2019-10-14 14:04:24

标签: node.js

我有一个这样的简化电话:

var post_req = http.request(post_options, function(post_result) {
            post_result.setEncoding('utf8');
        post_req.on('error', function(err) {//failfolder
            res.writeHead(400, {'Content-Type': 'application/json'});
            res.end(retdata);

            console.log(
                    "\x1b[37m", "Remote IP", "\x1b[32m", clientIp + ' ',
                    "\x1b[37m", 'Proxied apicall to:', "\x1b[32m", cfg.email_api + path + "\n",
                    "\x1b[31m", 'API call failed with reason:', err.message + "\n",
                    "\x1b[37m", 'API response:', "\x1b[32m", retdata + "\n",
                    "\x1b[37m", 'Stack:', "\x1b[32m", err.stack + "\n",
                    "\x1b[37m", 'Headers:', "\x1b[32m", post_req.rawHeaders + "\n",
                    "\x1b[37m", "=================================");
        });

上面console.log的stack部分显示以下内容

我们偶尔会收到解析错误

API response:
  Stack:  Error: Parse Error
    at Error (native)
    at Socket.socketOnData (_http_client.js:377:20)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:559:20)

我们不知道应该找到哪种问题。

升级到 v12.11.1

API call failed with reason: Parse Error: Expected HTTP/
  API response:
  Stack:  Error: Parse Error: Expected HTTP/
    at Socket.socketOnData (_http_client.js:456:22)
    at Socket.emit (events.js:210:5)
    at addChunk (_stream_readable.js:308:12)
    at readableAddChunk (_stream_readable.js:289:11)
    at Socket.Readable.push (_stream_readable.js:223:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:182:23)
  Headers:  undefined

1 个答案:

答案 0 :(得分:4)

我最近在使用 Parse Error: Expected HTTP/ 进行单元测试时遇到了 supertest。原来问题是 Content-Length 标头的值不正确。如果标头值小于实际内容大小,则 supertest 因上述错误而无法通过测试。 这可能是您的情况的一个提示。