使favicon.ico出现在网页的顶栏

Make favicon.ico appear at the top bar of the web page

我正在使用 node.js 到 运行 服务器。总是当我向它发出请求时,实际上会出现两个请求,一个是普通请求,一个是真实请求,一个是request/favicon.ico。所以我尝试发回 favicon.ico 因为我希望它出现在顶部栏中。但它并没有出现在那里。

我做错了什么?这是我的代码:

var http = require("http");

http.createServer(onRequest).listen(7777);
console.log("Server is running now.....");

function onRequest(request, response)
{
    console.log("A user made a request" + request.url);
    response.writeHead(200, {"Context-Type": "text/plain"});
    response.write("Here is some data");
    response.end();
}

然后我将文件 favicon.ico 放入我的 server.js 所在的同一文件夹中。

这个问题: 不适合我,因为答案和答案中的代码已被接受,因为它对我不起作用。

您可以通过在 html 页面的 head 标记中添加此行来完成此操作。

<link rel="icon" type="image/png" href=favicon.ico>

如果您直接使用 http 模块,那么您将必须检查每个请求的 request 对象,并为所有请求网站图标的请求自行提供网站图标文件。

在您的示例中,您必须在 onRequest() 函数中测试 request 对象,并为某些请求提供网站图标,并为其余请求提供原始内容。

如果您使用 Express 或其他带有 Connect 兼容中间件的框架,那么您将能够像这样使用模块:

如果您只想使用 http 模块而不使用 Express 或任何其他更高级别的框架,请参阅此答案以获取有关如何使用 http(以及 Express)提供静态图像的示例这将帮助你:

  • How to serve an image using nodejs

这应该有效

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

http.createServer(onRequest).listen(7777);
console.log("Server is running now.....");

function onRequest(request, response)
{
    console.log("A user made a request" + request.url);
    if (request.url === '/favicon.ico') {
      var fileStream = fs.createReadStream("./favicon.ico");
      return fileStream.pipe(response);
    }
    response.writeHead(200, {"Context-Type": "text/plain"});
    response.write("Here is some data");
    response.end();
}

但是如您所见,您必须为每个要处理的 url 创建一个特例。我建议使用像 express 这样的框架,它会让你的事情变得简单。

此外,借助框架,您可以在静态目录中拥有网站图标,这样您就不必在每次请求静态文件时都从文件系统中显式读取。