在HTTP服务器中设置favicon?

时间:2016-09-17 23:39:56

标签: node.js http favicon

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

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

1 个答案:

答案 0 :(得分:5)

归结为:

  • 如果请求的路径是您的favicon的路径,请提供它。
  • 否则,请执行您对请求所做的任何事情。

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

这意味着,在/favicon.ico投放您的favicon通常就足够了。

假设您的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);