我有一个小程序需要从使用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>
因此,我已经在客户端创建步骤中使用主机名的变体以及“www.apple.com”的url请求以几乎所有方式修改了上述代码,但通常我只是得到错误来自节点如下:
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
此外,我对使用Google服务获取favicon不感兴趣。
答案 0 :(得分: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
顺便提一下,这意味着他们的服务器工作不正常,但这是另一个讨论。
答案 1 :(得分: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
});
});