防止favicon.ico发出第二个请求 – Node.js

我试图阻止favicon.icoforms进行套接字连接时的第二个请求。

这是我的服务器:

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!'}); }); 

这似乎并不奏效。 我没有得到任何错误,但是当一个套接字连接时,两个图像从客户端加载,这看起来好像还有两个请求发生。

那么我的代码是完全错误的,还是我在正确的轨道上? 因为不pipe我的console.log()在我的服务器代码中,什么都不会打印到控制台上。

编辑:客户端

 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是全球性的。 我有(现在两个图像),一个#hero#hero1 。 当一个玩家连接两个图像被加载。

当您想要回应请求时,您不应该再打电话。 一般来说, writeHead()无效的,然后再调用。 大多数中间件希望能够处理尚未写入networking的响应。

你的“愚蠢的图标”中间件运行的原因是通过调用next在第一个调用它 。 你需要res.writeHead()res.end() 或者直接调用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头。