【问题标题】:Prevent favicon.ico from making a second request - Node.js防止 favicon.ico 发出第二个请求 - Node.js
【发布时间】:2013-10-14 01:17:13
【问题描述】:

我试图阻止 favicon.ico 表单在套接字连接时发出第二个请求。

这是我的服务器:

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

这似乎不起作用。我没有收到任何错误,但是当一个套接字连接时,会从客户端加载两个图像,这使得看起来仍然有两个请求发生。

那么是我的代码完全错误,还是我走在正确的轨道上?因为无论我在我的服务器代码中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。当一个播放器连接时,两个图像都会被加载。

【问题讨论】:

  • 你能显示你的客户端代码,哪个图像在那里加载了两次吗?

标签: javascript node.js socket.io connect


【解决方案1】:

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

你的“愚蠢的网站图标”中间件运行的原因是 你通过在第一个调用 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();
    }
}

或者,只需使用the builtin favicon middleware,它会做一些重要的事情,比如设置正确的Cache-Control 标头。

【讨论】:

  • 非常感谢。但是我的代码似乎仍然只在一个套接字连接后调用了两个图像。我不知道这是否是 favicon.ico 的错了。你介意快速浏览一下我之前的帖子吗? stackoverflow.com/questions/19202615/…
猜你喜欢
  • 2010-11-22
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-30
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多