【发布时间】: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