繁体   English   中英

从node.js开始,创建一个简单的http服务器,回调行为不符合预期

[英]Starting with node.js, creating a simple http server, callback not behaving as expected

我从node.js开始。 这是我正在关注的书 第一个示例是创建一个简单的http服务器。 作者精心解释了代码,然后开始逐步修改原始示例。 我遇到的问题是在标题为“事件驱动的异步回调”的部分中 有问题的代码在这里:

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

我对代码所做的唯一更改是修饰。 但是为了清楚起见,这是我的作品:

var http = require("http"),
    port = 1337;

function doHandleRequest(request, response) {
  console.log("Request received...");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Welcome to Node.js Kickstart!");
  response.end();
}

http.createServer(doHandleRequest).listen(port);
console.log("Listening at http://127.0.0.1:" + port + "\n");

无论如何,每次我刷新页面时,“ 请求收到...”消息应显示一次(?),但是该消息记录了两次 我在这里做错了什么?

这实际上不是Node的错。 这可能是浏览器的错误。

加载页面时,浏览器还会向<domain:port>/favicon.ico发出请求,以尝试获取网站的<domain:port>/favicon.ico图像(标签中显示的小图像)

例如, https://stackoverflow.com/favicon.ico

这就是为什么发生这种情况。

第一个要求

第二个请求

如您所见,有两个请求,一个是对“ /”的请求,另一个是对“ /favicon.ico”的请求,我正在使用eclipse调试代码

当您的浏览器请求URL时,它还将请求“ /favicon.ico”,从而向您的服务器发出2个请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM