初接触Nodejs,第一步就遇到问题

初接触Nodejs,第一步就遇到问题

var http = require(‘http’);
http.createServer(function (req, res) {
console.log(req.headers[‘user-agent’])
res.writeHead(200, {‘Content-Type’: ‘text/plain’});
res.end(‘Hello World\n’);

}).listen(1337, ‘127.0.0.1’);

这么一段简单的代码,为什么每次访问都是输出两次

Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)

很郁闷,难道一次请求,触发两次request事件?


7 回复

在Node.js中,HTTP服务器默认会监听两个端口事件:socketrequest。当客户端发起一个请求时,服务器会接收到两个事件,一个是socket事件,另一个是request事件。这可能是导致你看到输出两次的原因。

为了验证这一点,我们可以通过添加一些日志来查看具体发生了什么。下面是修改后的代码:

var http = require('http');

http.createServer(function (req, res) {
    // 输出用户代理信息
    console.log('Request received:', req.headers['user-agent']);
    
    // 设置响应头
    res.writeHead(200, {'Content-Type': 'text/plain'});
    
    // 发送响应数据
    res.end('Hello World\n');
    
}).listen(1337, '127.0.0.1', function() {
    console.log('Server running at http://127.0.0.1:1337/');
});

在这个例子中,我们只关注了request事件。为了确保我们只处理一次请求,可以考虑使用中间件或更复杂的逻辑来过滤掉不需要的事件。

如果你仍然看到重复的日志输出,那么可能是因为客户端发送了多个请求。你可以通过检查请求的URL或其他标识符来区分不同的请求。例如:

http.createServer(function (req, res) {
    // 输出用户代理信息
    console.log('Request received:', req.headers['user-agent'], 'from URL:', req.url);
    
    // 设置响应头
    res.writeHead(200, {'Content-Type': 'text/plain'});
    
    // 发送响应数据
    res.end('Hello World\n');
    
}).listen(1337, '127.0.0.1', function() {
    console.log('Server running at http://127.0.0.1:1337/');
});

通过这种方式,你可以更好地理解每个请求的具体来源,并且能够更容易地调试和定位问题。


看了文档的解释似乎是这样

Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of keep-alive connections)

不过这样不太靠谱啊?一次连接多次请求,求解释。

你加上 timestamp 试试。我运行你的代码没出问题。

$ node test21.js
Wget/1.13.4 (linux-gnu)

$ wget http://127.0.0.1:1337 –2013-04-26 10:47:56-- http://127.0.0.1:1337/ Connecting to 127.0.0.1:1337… connected. HTTP request sent, awaiting response… 200 OK Length: unspecified [text/plain] Saving to: `index.html’

[ <=>                                                        ] 12          --.-K/s   in 0s      

2013-04-26 10:47:56 (390 KB/s) - `index.html’ saved [12]

我这边一次访问出现了3次。。。

有的浏览器会自动发起对favo.ico的请求.

学习了。

在你的代码中,console.log(req.headers['user-agent']) 输出了两次是因为浏览器发出了两次请求。通常情况下,浏览器会发送一个主要请求(通常是HTML文件)以及一个 favicon.ico 请求。这就是为什么你会看到相同的 user-agent 被打印两次。

如果你不希望看到这种行为,可以通过检查请求路径来过滤掉对 favicon.ico 的请求。以下是修改后的代码示例:

var http = require('http');

http.createServer(function (req, res) {
    if (req.url === '/favicon.ico') {
        // 忽略对 favicon.ico 的请求
        res.writeHead(200, {'Content-Type': 'image/x-icon'});
        res.end();
        return;
    }
    
    console.log(req.headers['user-agent']);
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

在这个修改后的版本中,我们检查了请求的 URL 是否为 /favicon.ico,如果是,则直接返回一个空响应,并忽略进一步处理。这样可以避免输出两次相同的 user-agent

回到顶部