Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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.

Problem courtesy of: Nilzone-

Solution

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.

Solution courtesy of: josh3736

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×