【问题标题】:Node.js HEAD request returns HPE_INVALID_CONTENT_LENGTH errorNode.js HEAD 请求返回 HPE_INVALID_CONTENT_LENGTH 错误
【发布时间】:2014-07-02 18:32:11
【问题描述】:

使用 request 模块时,我在对某些缩短的 301 重定向 URL 的 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 请求此 URL 的结果:

$ 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

body 上的内容长度实际上是 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。

【问题讨论】:

  • 请求模块终于被弃用了。

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


【解决方案1】:

它适用于普通节点 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 了解它。

更新: 使用普通节点重现错误,问题不是缩短的 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

【讨论】:

  • 谢谢,之前从未使用过 http.request,但我认为这很清楚这是 request 的错误 - 我会提出问题。
  • 哦,我什至没有注意到您是在 GitHub 上回复的同一个人。无论如何,是的,你是完全正确的,很抱歉误报。我已经看到很多网站现在都这样做了。因此,为了不缩短缩短的 URL,我们必须切换到 GET:github.com/Swizec/node-unshortener/pull/19/files
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 2019-12-18
  • 2019-01-25
  • 2019-11-12
  • 1970-01-01
  • 2017-01-10
  • 2019-07-28
相关资源
最近更新 更多