Search code examples
javascriptnode.jsexpresscontent-typefavicon

How to add favicon for Content-Type: application/json


I am using node.js and implementing an API that returns a response as Content-Type: application/json like this:

module.exports={
    api: (req, res) => {
        let data = {"data": [1, 2, 3]};
        res.status(200).json(data);
    }
}

But, there is no favicon that can be viewed when trying that API on the browser. I see another website that can get this done.

api

How can add a favicon on the Node.js API with Content-Type: application/json?


Solution

  • Can't believe people are suggesting some package for this simple operation.

    All browsers request /favicon.ico looking for favicon so you have to respond to this request.

    app.get('/favicon.ico', (req, res) => {
      res.sendFile(path.join(__dirname, 'assets/favicon.ico'))
    })
    
    app.get('/api/foo', (req, res) => {
      res.json({ foo: 'bar' })
    })
    
    

    enter image description here

    Note: I used duckduckgo's favicon