node.js Express js 防止 GET /favicon.ico

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35408729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:55:08  来源:igfitidea点击:

Express js prevent GET /favicon.ico

node.jsexpress

提问by user233232

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?

在每个请求中,我的服务器都接收到 /favicon.ico 的 GET 请求,即使它是不包含 html 文件的 REST api。为什么会发生这种情况以及如何阻止此请求?

回答by duncanhall

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

默认情况下,浏览器将尝试/favicon.ico从主机名的根请求,以便在浏览器选项卡中显示一个图标。

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

如果您想避免此请求返回 404,您可以:

  • Supply a favicon.icofile that is available at the root of your site.
  • Use a module such as serve-faviconto point requests to a specific file.
  • Catch the favicon.icorequest and send a 204 No Contentstatus:

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

  • favicon.ico提供在您的站点根目录下可用的文件。
  • 使用诸如serve-favicon 之类的模块将请求指向特定文件。
  • 捕获favicon.ico请求并发送204 No Content状态:

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

回答by Blair Anderson

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

回答by jwerre

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

我同意@Blair Anderson 的观点,中间件是这里最好的行动方案,但204不应返回 body。此外,您可能想要捕获所有图标请求,例如:https://example.com/some/path/favicon.ico。在这种情况下,这样的事情最有效:

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

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

  return next();

});

回答by Marco Alka

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)

我认为您的意思是您的服务器收到了这样的请求。通常,浏览器会尝试在选项卡上显示一个图标。尤其是 Chrome 非常具有攻击性(至少这是我的观察)。
您可以做的是正确处理对 HTML 页面的请求,并在 API 调用时忽略它(因为它们通常不会在浏览器的前台发生)