Open In App

How to return/favicon.ico as req.url in ExpressJS ?

Favicon is the small icon you see in the tab, left of the title… depending on the user’s browser it may (or not) ask for that file, associated with a particular website or web page.

Node.js is an open source and cross-platform runtime environment for executing JavaScript code outside the browser. It is widely used in developing APIs and microservices from small to large companies.



Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middle ware and routing; it adds helpful utilities to Node.js’s HTTP objects; it facilitates the rendering of dynamic HTTP objects.

Installing Modules :



npm install http

Example:




var http = require('http');
  
http.createServer(function (q, r) {  
  
 // control for favicon
  
 if (q.url === '/favicon.ico') {
   r.writeHead(200, {'Content-Type': 'image/x-icon'} );
   r.end();
   console.log('favicon requested');
   return;
 }
  
 // not the favicon? say hai
 console.log('hello');
 r.writeHead(200, {'Content-Type': 'text/plain'} );
 r.write('Hello, world!');
 r.end();
   
}).listen(8000);
  
console.log('Server running at http://127.0.0.1:8000/');

node index

Output:

Article Tags :