Express js prevent GET /favicon.ico

2020-02-17 09:00发布

In every request, my server is receiving GET request to /favicon.ico, even when it's REST api that not include html file. Why is this happening and how can I prevent this request?

4条回答
疯言疯语
2楼-- · 2020-02-17 09:25

Browsers will by default try to request /favicon.ico from the root of a hostname, in order to show an icon in the browser tab.

If you want to avoid this request returning a 404, you can either:

  • Supply a favicon.ico file that is available at the root of your site.
  • Use a module such as serve-favicon to point requests to a specific file.
  • Catch the favicon.ico request and send a 204 No Content status:

    app.get('/favicon.ico', (req, res) => res.status(204));

查看更多
▲ chillily
3楼-- · 2020-02-17 09:25

my preferred method is middleware

put this somewhere:

function ignoreFavicon(req, res, next) {
  if (req.originalUrl === '/favicon.ico') {
    res.status(204).json({nope: true});
  } else {
    next();
  }
}

then:

app.use(ignoreFavicon);
查看更多
相关推荐>>
4楼-- · 2020-02-17 09:26

I agree with @Blair Anderson that middleware is the best course of action here but 204 should not return a body. Also, you may want to catch all favicon request e.g.: https://example.com/some/path/favicon.ico. In which case something like this works best:

app.use( function(req, res, next) {

  if (req.originalUrl && req.originalUrl.split("/").pop() === 'favicon.ico') {
    return res.sendStatus(204);
  }

  return next();

});
查看更多
beautiful°
5楼-- · 2020-02-17 09:50

I think you mean that your server receives such a request. Usually, the browser will try to get an icon to display on the tab. Especially Chrome is very aggressive (at least that's my observation).
What you can do is properly handle the request for your HTML pages and ignore it for API calls (as they will probably normally not happen in the foreground with a browser)

查看更多
登录 后发表回答