【问题标题】:Set favicon in HTTP server?在 HTTP 服务器中设置网站图标?
【发布时间】:2016-09-18 22:12:25
【问题描述】:

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

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

【问题讨论】:

  • 你应该澄清你的问题。 “设置网站图标”是什么意思?对我来说,这意味着“服务”,显然@noisypixy 也这么认为。
  • 如果它不是“服务”网站图标,那么我怀疑与 HTML 方面更相关。
  • @philippe_b “服务”一个网站图标意味着您在 HTML 页面的正文中显示它。 “设置”一个 favicon 意味着在 favicon 所在选项卡的左侧显示 favicon。
  • @bjskistad “服务”一个网站图标,对大多数人来说,意味着允许它通过 HTTP 请求提供给客户端。这也是能够在选项卡中显示它所需要的。这也是这个问题的答案所实现的。

标签: node.js http favicon


【解决方案1】:

归结为:

  • 如果请求的路径是您的网站图标的路径,则提供它。
  • 否则,对请求执行任何操作。

除非您在 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);

【讨论】:

  • 我正在尝试设置图标,而不是提供它。
  • @bjskistad 我觉得这个答案是合理的,即使这不是你想要的。如果您不赞成,我建议您撤消此操作。
  • 为了以防万一,我将其编辑为对初学者更友好。不过,我并不特别介意投反对票。
  • @noisypixy 谢谢,我相信这对其他人会有所帮助。
  • 不确定是否严重。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多