在 HTTP 服务器中设置图标?

Set favicon in HTTP server?

我正在使用 Node.js HTTP 模块创建服务器,我想知道如何在 HTTP 服务器中设置网站图标(快捷方式图标)?我搜索了这个,我看到Express可以设置favicon,但是我没有找到任何HTTP解决方案。

我该如何做到这一点? (不迁移到 Express)

归结为:

  • 如果请求的路径是您的网站图标的路径,请提供它。
  • 否则,请执行您正在处理的请求。

除非您在 HTML 文档中更改您的网站图标的路径,否则浏览器(通常)会向 /favicon.ico 路径发出请求以获取您的服务器的网站图标。

这意味着,在 /favicon.ico 提供您的网站图标通常就足够了。

假设您的网站图标位于 ./public/favicon.ico,并将在您服务器的 /favicon.ico 路径提供服务,您可以这样做:

var http = require('http');
var path = require('path');
var fs = require('fs');
var url = require('url');

var server = http.createServer();

// Location of your favicon in the filesystem.
var FAVICON = path.join(__dirname, 'public', 'favicon.ico');

var server = http.createServer(function(req, res) {
  var pathname = url.parse(req.url).pathname;

  // If this request is asking for our favicon, respond with it.
  if (req.method === 'GET' && pathname === '/favicon.ico') {
    // MIME type of your favicon.
    //
    // .ico = 'image/x-icon' or 'image/vnd.microsoft.icon'
    // .png = 'image/png'
    // .jpg = 'image/jpeg'
    // .jpeg = 'image/jpeg'
    res.setHeader('Content-Type', 'image/x-icon');

    // Serve your favicon and finish response.
    //
    // You don't need to call `.end()` yourself because
    // `pipe` will do it automatically.
    fs.createReadStream(FAVICON).pipe(res);

    return;
  }

  // This request was not asking for our favicon,
  // so you can handle it like any other request.

  res.end();
});

// Listen on port 3000.
//
// This line is not relevant to this answer, but
// it would feel incomplete otherwise.
server.listen(3000);