I am using node.js to run the server. Always when I make a request to it actually there are occur two requests, one of which is an ordinary one, which was truly made and one is request/favicon.ico
. So I tried to send favicon.ico
back because I want it to appear in the top bar. But it just doesn`t appear there.
What am I doing wrong? Here is my code:
var http = require("http");
http.createServer(onRequest).listen(7777);
console.log("Server is running now.....");
function onRequest(request, response)
{
console.log("A user made a request" + request.url);
response.writeHead(200, {"Context-Type": "text/plain"});
response.write("Here is some data");
response.end();
}
And I put file favicon.ico into the same folder my server.js
is.
This question:Set favicon in HTTP server? is not appropriate for me since the answer and code in answer, which were accepted, for it don`t work for me.
This should work
var http = require("http");
var fs = require("fs");
http.createServer(onRequest).listen(7777);
console.log("Server is running now.....");
function onRequest(request, response)
{
console.log("A user made a request" + request.url);
if (request.url === '/favicon.ico') {
var fileStream = fs.createReadStream("./favicon.ico");
return fileStream.pipe(response);
}
response.writeHead(200, {"Context-Type": "text/plain"});
response.write("Here is some data");
response.end();
}
But as you can see you have to create a special case for each url you want to handle. I recommend using a framework like express which will make things easy for you.
Also with framework you can have favicon in static directory so you won't have to explicitly read from file system on each request for static files.