Prevent favicon.ico from making a second request - Node.js
Asked Answered
M

1

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.

Monophonic answered 7/10, 2013 at 12:44 Comment(1)
Can you show your client side code, which image is loaded there twice ?Spue
R
8

You're not supposed to call next when you want to respond to a request. Generally, it's not valid to writeHead() and then call next. Most middleware expects to work with a response that has not written to the network yet.

The reason your "stupid favicon" middleware runs is that you're calling it it by invoking next in the first one. You need to res.writeHead() and res.end() OR just call 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();
    }
}

Alternatively, just use the builtin favicon middleware, which does important things like setting proper Cache-Control headers.

Ratline answered 7/10, 2013 at 20:6 Comment(1)
thanks a lot. But My code still seems to call two images after only one socket connects. I don't know if this is the favicon.ico's fault anymore. Would you mind taking a quick look at my previous post? #19203115Monophonic

© 2022 - 2024 — McMap. All rights reserved.