在HTTP服务器中设置favicon?

bar*_*tad 4 favicon http node.js

我正在使用Node.js HTTP模块来创建服务器,我想知道,如何在HTTP服务器中设置favicon(快捷图标)?我搜索了一下,我看到Express可以设置favicon,但我找不到任何HTTP解决方案.

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

noi*_*ixy 8

归结为:

  • 如果请求的路径是您的favicon的路径,请提供它.
  • 否则,做你正在做的任何请求.

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

这意味着,为您的图标服务/favicon.ico通常就足够了.

假设您的favicon位于服务器./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);
Run Code Online (Sandbox Code Playgroud)

  • @bjskistad我发现这个答案是合理的,即使这不是你想要的.如果您将其投票,我建议您撤消此操作. (3认同)
  • 不确定是否严重。 (2认同)