Node.js HEAD请求返回HPE_INVALID_CONTENT_LENGTH错误

Node.js HEAD request returns HPE_INVALID_CONTENT_LENGTH error

本文关键字:INVALID CONTENT LENGTH 错误 HPE js HEAD 请求 返回 Node      更新时间:2023-09-26

使用请求模块,我在HEAD请求到一些缩短的301重定向url时得到以下错误:

{ [Error: Parse Error] bytesParsed: 123, code: 'HPE_INVALID_CONTENT_LENGTH' }

例如,我在http://cnb.cx/1vtyQyv上得到这个。非常容易复制(节点v0.10.29,请求v2.36.0):

var request = require('request');
request({ url:'http://cnb.cx/1vtyQyv', method: 'HEAD' }, function(err, res) {
    console.log(err, res);
});

下面是curl HEAD请求的结果:

$ curl -I http://cnb.cx/1vtyQyv
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 02 Jul 2014 18:16:05 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Cache-Control: private; max-age=90
Content-Length: 124
Location: http://www.cnbc.com/id/101793181
Mime-Version: 1.0
Set-Cookie: _bit=53b44c65-00194-0369a-281cf10a;domain=.cnb.cx;expires=Mon Dec 29 18:16:05 2014;path=/; HttpOnly

正文上的内容长度实际上是124,可以通过curl http://cnb.cx/1vtyQyv | wc -c

验证。

错误是从Node.js的核心http解析器(https://github.com/mattn/http-server/blob/master/http_parser.c)中抛出的,然而,奇怪的是,request能够遵循此301重定向并成功返回目标页面(http://www.cnbc.com/id/101793181)的内容,在做GET请求时没有错误,这表明错误是不必要的:

var request = require('request');
request({ url:'http://cnb.cx/1vtyQyv', method: 'GET' }, function(err, res) {
    console.log(err, res);
});

这是一个使用node-unshortener的问题,它会重复HEAD请求直到找到完整的URL。

它适用于普通节点v0.10.29:

var http = require('http');
http.request({
  host: 'cnb.cx',
  path: '/1vtyQyv',
  method: 'HEAD'
}, function(res) {
  console.dir(res);
  res.resume();
}).end();

该错误在request v2.36.0中重现。你可能想要就此提出一个问题

UPDATE:普通节点出现错误,问题不是URL缩短,而是重定向的URL导致问题:

http.request({
  host: 'www.cnbc.com',
  path: '/id/101793181',
  method: 'HEAD'
}, function(res) {
  console.dir(res.statusCode);
  console.dir(res.headers);
}).end();
// results in:
//
// events.js:72
//         throw er; // Unhandled 'error' event
//               ^
// Error: Parse Error
//     at Socket.socketOnData (http.js:1583:20)
//     at TCP.onread (net.js:527:27)

更新# 2:事实证明,重定向的URL返回Content-Length: -1,这是导致错误的原因。curl -I http://www.cnbc.com/id/101793181显示:

HTTP/1.1 200 OK Date: Wed, 02 Jul 2014 22:23:49 GMT Server: Apache Vary: User-Agent Via: 1.1 aicache6 Content-Length: -1 X-Aicache-OS: 10.10.1.25:80 Connection: Keep-Alive Keep-Alive: max=20