使用Node.js获取网站图标

3

我有一个小程序需要使用node.js从网站中获取favicon。这在大多数情况下都有效,但是在apple.com上,我遇到了无法理解或修复的错误:

    var sys= require('sys');
    var fs= require('fs');
    var http = require('http');

    var rurl = http.createClient(80, 'apple.com');
    var requestUrl = 'http://www.apple.com/favicon.ico';
    var request = rurl.request('GET', requestUrl, {"Content-Type": "image/x-icon", "host" : "apple.com" });
    request.end();

    request.addListener('response', function (response)
    {
            response.setEncoding('binary');
            var body = '';
            response.addListener('data', function (chunk) {
                    body += chunk;
            });
            response.addListener("end", function() {
            });
    });

当我发送这个请求时,响应如下:
<head><body> This object may be found <a HREF="http://www.apple.com/favicon.ico">here</a> </body>

因此,我已经以客户端创建步骤中主机名的变体和url请求为“www.apple.com”的方式修改了上述代码,但通常我只会从节点中获得以下错误:
node.js:63
    throw e;
    ^
Error: Parse Error
    at Client.ondata (http:901:22)
    at IOWatcher.callback (net:494:29)
    at node.js:769:9

此外,我不想使用谷歌服务来获取站点图标。
2个回答

4

您在请求中的主机设置应为www.apple.com(带有www),为什么要在请求中包含Content-Type头?这毫无意义。相反,您应该使用Accept:image / x-icon

我从该网址获得了此响应:

$ curl -I http://www.apple.com/favicon.ico
HTTP/1.1 200 OK
Last-Modified: Thu, 12 Mar 2009 17:09:30 GMT
ETag: "1036-464ef0c1c8680"
Server: Apache/2.2.11 (Unix)
X-Cache-TTL: 568
X-Cached-Time: Thu, 21 Jan 2010 14:55:37 GMT
Accept-Ranges: bytes
Content-Length: 4150
Content-Type: image/x-icon
Cache-Control: max-age=463
Expires: Sun, 12 Sep 2010 14:22:09 GMT
Date: Sun, 12 Sep 2010 14:14:26 GMT
Connection: keep-alive

它不应该有任何问题解析那个……而且我也得到了图标数据。

这是我使用非 www 主机头收到的响应:

$ curl -I http://www.apple.com/favicon.ico -H Host: apple.com
HTTP/1.0 400 Bad Request
Server: AkamaiGHost
Mime-Version: 1.0
Content-Type: text/html
Content-Length: 208
Expires: Sun, 12 Sep 2010 14:25:03 GMT
Date: Sun, 12 Sep 2010 14:25:03 GMT
Connection: close

HTTP/1.1 302 Object Moved
Location: http://www.apple.com/
Content-Type: text/html
Cache-Control: private
Connection: close

顺便提一下,这两个问题同时出现,意味着他们的服务器出现了故障,但这是另一个讨论话题。

更改主机并使用 Accept: image/x-icon,结果是:<head><body> 可以在 <a HREF="http://www.apple.com/favicon.ico">此处</a> 找到该对象 </body> - jimt
1
@jimt 嗯,重要的部分是主机头,而不是接受的内容... - Tor Valamo

1

这段代码对我来说似乎可以工作

var sys = require("sys")
  , fs = require("fs")
  , http = require("http");

var client = http.createClient(80, "www.apple.com") // Change of hostname here and below
  , req = client.request( "GET"
                        , "http://www.apple.com/favicon.ico"
                        , {"Host": "www.apple.com"});

req.end();

req.addListener("response", function (res) {
  var body = "";
  res.setEncoding('binary');
  res.addListener("data", function (c) {
    body += c;
  });
  res.addListener("end", function () {
    // Do stuff with body
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接