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

Jor*_*rdy 3 javascript favicon content-type node.js express

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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.

应用程序编程接口

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

bog*_*off 5

不敢相信人们为这个简单的操作建议一些软件包。

所有浏览器都请求/favicon.ico查找网站图标,因此您必须响应此请求。

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

app.get('/api/foo', (req, res) => {
  res.json({ foo: 'bar' })
})

Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

注意:我使用了duckduckgo的favicon

  • 如果您想使用的话,这个实际上允许您发送 png/gif 格式的图标。 (2认同)