-1

When loging the OnRequest function below (found in this tut http://www.nodebeginner.org/)

var http = require("http");

function onRequest(request, response) {
  console.log("Request received.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888);

console.log("Server has started.");

log will print "Request received." twice each time I refresh the webpage only once : this is annoying since it means I can have side effects when making some other processing.

Why doesn't node.js mitigate this like other http servers ?

My question is not WHY I know why, my question is HOW to detect that it is second time and avoid calling a heavy processing twice ?

4

2 回答 2

1

要忽略 favicon 请求,只需读取请求对象的 URL 属性,然后处理请求。如果您愿意,也可以发送404 Not Found

http.createServer(function (req, res) { 
  if (req.url === '/favicon.ico') {
    res.writeHead(200, {'Content-Type': 'image/x-icon'});
    res.end();
    return;
  }

  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello, world!');
}).listen(80);

此外,您关于其他 Web 服务器如何处理网站图标请求的陈述是不正确的。例如在 Nginx 中,请求的处理方式与任何其他请求一样,这通常会导致 HTTP 日志中出现许多“找不到文件”错误。

于 2013-09-02T01:29:34.253 回答
0

favicon.ico 可能还有一个额外的请求。

编辑:

因此,例如,在这种情况下,解决方案是忽略对某些路径的请求。

例如:

yourdomain.com/favicaon.ico

将不会遇到 (404) 响应,而

yourdomain.com/some/infinitely/more/important/path

以计算成本更高的响应得到确认。但是如果有人确实请求了这个 url 两次,你需要确认他们两次。你有没有遇到过 google 莫名其妙无法加载的情况?HTTP 并不完美,网络数据会丢失。如果他们在您点击刷新后决定不响应怎么办?没有更多的谷歌为您服务!

例如你可以做这样的事情

http.createServer(function (req, res) { 
    if (req.url.matches(/some\/important\/path/i') { 
        res.writeHead(200);//May need to add content-type, may not.
        res.write(someFunctionThatReturnsData());
        res.end();
    } else {//For favicon and other requests just write 404s
        res.writeHead(404);
        res.write('This URL does nothing interesting');
        res.end();
    }
}).listen(80);
于 2013-08-26T13:58:44.257 回答