Express js prevent GET /favicon.ico

前端 未结 4 1555
忘掉有多难
忘掉有多难 2020-12-07 23:13

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 r

相关标签:
4条回答
  • 2020-12-07 23:31

    my preferred method is middleware

    put this somewhere:

    function ignoreFavicon(req, res, next) {
      if (req.originalUrl.includes('favicon.ico')) {
        res.status(204).end()
      }
      next();
    }
    

    then:

    app.use(ignoreFavicon);
    
    0 讨论(0)
  • 2020-12-07 23:44

    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));

    0 讨论(0)
  • 2020-12-07 23:45

    In Case of web apps, we should supply a favicon.ico from static resources either serving directly via vanilla or by making use of express middleware serve-favicon

    In the case of API apps, we should supply 204 (no content) status code which will result in a success roundtrip.

    We can make use of sendStatus() method to respond with status code 204 (no content)

    app.get('/favicon.ico', function(req, res) { 
        res.sendStatus(204); 
    });
    

    if you are using status(204) make sure to use end() as well. Otherwise, the request will remain in pending status.

    app.get('/favicon.ico', function(req, res) { 
        res.status(204);
        res.end();    
    });
    
    0 讨论(0)
  • 2020-12-07 23:50

    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();
    
    });
    
    0 讨论(0)
提交回复
热议问题