Node.js HEAD请求返回HPE_INVALID_CONTENT_LENGTH错误

时间:2014-07-02 18:32:11

标签: javascript node.js redirect httprequest content-length

使用request模块我在对一些缩短的301重定向网址的HEAD请求中收到以下错误:

{ [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的核心h​​ttp解析器(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请求。

1 个答案:

答案 0 :(得分:3)

它适用于普通节点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重现了该错误。您可能希望file an issue了解它。

更新:错误是使用普通节点重现的,问题不是缩短的网址,而是导致问题的重定向网址:

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

相关问题