2013-08-25 57 views
-1

当登录电子下面OnRequest功能烦恼node.js中调用的httpserver回调函数两次,一个页面刷新

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

日志将打印(在此啧啧http://www.nodebeginner.org/发现)“收到的请求。”每次刷新网页一次两次:这很烦人,因为这意味着在进行其他处理时可能会产生副作用。

为什么node.js不像其他http服务器那样缓解这种情况?

我的问题不是为什么我知道为什么,我的问题是如何检测到它是第二次,避免重复处理两次?

+0

[Node.js可能重复 - 为什么我的回调被每次请求调用3次?](http://stackoverflow.com/questions/5369506/node-js-why-does-my-callback-get - 每次请求3次) –

+2

尝试'console.log(request.url)',你会看到原因。 –

+0

我的问题不是为什么我知道为什么,我的问题是如何检测到它是第二次,避免重复处理两次? – user310291

回答

0

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

编辑:

因此,在这种情况下,例如该溶液中,将忽略对于某些路径的请求。

例如:

yourdomain.com/favicaon.ico 

会与没有(404)响应来满足,而

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

与更昂贵的计算响应被确认。但是如果有人确实要求这个URL两次,你需要两次确认它们。你有没有谷歌只是莫名其妙地加载? HTTP并不完美,网络数据会丢失。如果他们在刷新后决定不作出回应会怎么样?没有更多的GOOGLE适合你!

例如,你可以做这样的事情

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

要忽略图标请求,刚刚看了你的请求对象的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日志中出现很多“文件未找到”错误。