Wednesday 20 February 2019

Node.js: Express: handling favicon


favicon.ico is known as website icon. When you bookmark a website, browser associates the website icon with the website in the bookmark.

Let’s see with an example

index.js
const express = require('express')

const app = express()

const port = 8080

app.get('/', (req, res) => res.send('Welcome to home page'))

app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Run index.js file by executing the command ‘node index.js’.


Open browser and hit the url ‘http://localhost:8080/’.


You can even send custom response code, if the favicon is not provided by your application.

app.get('/favicon.ico', (req, res) => {
         return res.sendStatus(204)
})
Response code 204 used to represent No Content.

index.js
const express = require('express')

const app = express()

const port = 8080

app.get('/', (req, res) => res.send('Welcome to home page'))

app.get('/favicon.ico', (req, res) => {
 return res.sendStatus(204)
})

app.listen(port, () => console.log(`Application started listening on port ${port}!`));


Run index.js and open the url ‘http://localhost:8080/’, you can see the status code as 204.


Previous                                                 Next                                                 Home

No comments:

Post a Comment