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

我在我的项目中使用节点js与expression框架和socket.io

当我在浏览器(这个地址: http:// localhost:3001 /testing )加载testing页时,每一件事情都很好,并在服务器日志中打印“ 用户连接 ”,但当我再次刷新页面打印该消息两次和另一个刷新打印该消息三次,每刷新一次重复该消息。

我的代码有什么问题?

谢谢。

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; 

Solutions Collecting From Web of "我的命令在节点js中的每个刷新页面重复"

您正在每个GET /请求中添加一个附加的事件处理程序。

您只需要在http路由之外添加一次事件处理程序。 把它看作是一条路线的等价物。

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