在HTTP服务器中设置favicon? [英] Set favicon in HTTP server?
问题描述
我正在使用Node.js HTTP模块来创建服务器,我想知道如何在HTTP服务器中设置favicon(快捷方式图标)?我搜索了一下,我看到Express可以设置favicon,但我找不到任何HTTP解决方案。
I'm using Node.js HTTP module to create a server, and I'm wondering, how do I set the favicon (shortcut icon) in a HTTP server? I searched this up, and I saw that Express can set the favicon, but I didn't find any HTTP solution.
我如何做到这一点? (没有迁移到Express)
How do I accomplish this? (Without migrating to Express)
推荐答案
归结为:
- 如果请求的路径是您的favicon的路径,请提供它。
- 否则,请执行您对请求所做的任何操作。
除非您在HTML文档中更改了favicon的路径,否则浏览器(通常)会向 / favicon发出请求。 ico
路径以获取服务器的favicon。
Unless you change the path to your favicon in an HTML document, browsers will (usually) make a request to the /favicon.ico
path in order to get the favicon of your server.
这意味着,在 / favicon服务你的favicon。 ico
通常已足够。
That means, serving your favicon at /favicon.ico
is often enough.
假设您的favicon位于 ./ public / favicon.ico
,并将在您服务器的 /favicon.ico
路径中提供,您可以执行以下操作:
Assuming your favicon is located at ./public/favicon.ico
, and will be served at the /favicon.ico
path in your server, you can do something like this:
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);
这篇关于在HTTP服务器中设置favicon?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!