我的命令重复节点js中的每个刷新页面

时间:2017-04-21 08:57:19

标签: node.js express socket.io

我在项目中使用带有快速框架和socket.io的节点j。

当我在浏览器中加载测试页面时(使用此地址:http://localhost:3001/test),每件事情都很好并打印" 用户连接"在服务器日志中,但是当我再次刷新页面时,打印该消息两次并使用另一次刷新打印该消息三次并且每次刷新都重复该消息。

我的代码中有什么问题?

感谢。

test.js

var express = require('express');
var router = express.Router();
var io = require('../app');

router.get('/', function(req, res, next) {

    io.on('connection', function(socket){
        console.log('a user connected');
    });

    res.render('test', { title: 'test' });
});

module.exports = router;

app.js

    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var session = require('express-session')
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');

    var app = express();
    var server = require('http').Server(app);
    var io = require('socket.io')(server);

    server.listen(3001);

    module.exports = io;

    var index = require('./routes/index');
    var users = require('./routes/users');
    var test = require('./routes/test');

    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'hbs');

    // uncomment after placing your favicon in /public
    //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

    app.use('/', index);
    app.use('/users', users);
    app.use('/test', test);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
    });

    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });

    module.exports = app;

1 个答案:

答案 0 :(得分:2)

您要在每个GET /请求中添加其他事件处理程序。

您只需要在http路由之外添加一次事件处理程序。可以把它想象成一条路线的socketio。

var io = require('socket.io')(server);

io.on('connection', function(socket){
  console.log('a user connected');
});

然后在您的路由器中,只需处理http请求

router.get('/', function(req, res, next) {
  res.render('test', { title: 'test' });
});