Skip to content
Related Articles

Related Articles

How to return/favicon.ico as req.url in ExpressJS ?
  • Last Updated : 13 Apr, 2021

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
  • Importing Modules :



    var http = require('http');
  • createServer(): Run Node.js in main.js : node main.js in terminal. Ended as soon as it got started; we made a server but didn’t make it active.

    let http = require('http');
    let server = http.createServer();
  • listen(): Listen for the 8000 port. Got connected; But, the server keeps waiting for response.

    let http = require('http');
    let server = http.createServer();
    server.listen(8000);
  • response(): The response.write() can take only a string.

    http.createServer(function (q, r) {
       r.writeHead('hi' );
       r.end();
    });
  • Understanding URLs:The HTTP 200, is to indicate the request has been fulfilled and resulted in a new resource being created
    http.createServer(function (q, r) {  
       if (q.url === '/favicon.ico') {
         r.writeHead(200, {'Content-Type': 'image/x-icon'} );
         r.end();
         console.log('favicon requested');
         return;
       }
  • Change Query Strings 
    //  if not favicon
     console.log('hello');
     r.writeHead(200, {'Content-Type': 'text/plain'} );
     r.write('Hello, world!');
     r.end();
    }).listen(8000);

Example:

index.js




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:

My Personal Notes arrow_drop_up
Recommended Articles
Page :