6

I'm trying to prevent favicon.ico form making a second request when a socket connects.

Here is my server:

var io = require('socket.io'),
connect = require('connect');

var app = connect()
.use(connect.static('public'))
.use(function(req, res, next){
    if (req.url === '/favicon.ico') {
        res.writeHead(200, {'Content-Type': 'image/x-icon'} );
        next();
    }
})
.use(function(req, res){
    res.end('stupid favicon...');   
}).listen(3000);

var game = io.listen(app);

game.sockets.on('connection', function(socket){
    socket.emit('entrance', {message: 'Welcome to the game!'});

    socket.on('disconnect', function(){
        game.sockets.emit('exit', {message: 'A player left the game...!'});
    });
    game.sockets.emit('entrance', {message: 'Another gamer is online!'});
});

This does not seem to work. I get no errors, but when one socket connects, two images is loaded from the client side, which makes it seem like there is still two requests happening.

So is my code completely wrong, or am I on the right track? Because no matter what I console.log() in my server-code, nothing is printed to the console.

EDIT: Client side

var socket = io.connect('http://localhost:3000');

    socket.on('entrance', function(data){
        console.log(data.message);

        var num = (count > 0) ? count : '';
        console.log("hero" + num);

        var hero = new Car("hero" + num);
        hero.init();

        count++;
    });

count is global. I have (for now two images), one #hero and #hero1. When one player connects both images are loaded.

4

1 回答 1

8

next当您想响应请求时,您不应该打电话。writeHead()一般情况下,先调用然后调用是无效的next。大多数中间件希望使用尚未写入网络的响应。

您的“愚蠢的网站图标”中间件运行的原因是通过调用next第一个中间件来调用它。您需要res.writeHead()res.end() OR只需调用next.

function(req, res, next){
    if (req.url === '/favicon.ico') {
        res.writeHead(200, {'Content-Type': 'image/x-icon'} );
        res.end(/* icon content here */);
    } else {
        next();
    }
}

或者,只需使用内置的 favicon 中间件,它会做一些重要的事情,比如设置正确的Cache-Control标题。

于 2013-10-07T20:06:00.210 回答