express.io with express router返回错误

时间:2015-07-02 15:11:49

标签: node.js express socket.io express.io

当我尝试从express.io上的客户端发出'ready'事件时,它显示错误

  

{route:[Function],broadcast:[Function]}'req.io.route'   TypeError:Object#没有方法'ready

我使用的是快递版express@4.12.4。

app.js如下所示

    var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express.io')();
app.http().io();
//var app = express();


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

// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
app.use('/users', users);

和index.js文件如下

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

/* GET home page. */
router.all('/', function(req, res, next) {
  res.render('index', { title: 'Express' });


    req.io.route('ready', function(res) {
         console.log('tested..........');
    })


});

module.exports = router;

客户端代码如下

<script>

  var socket;
 $(document).ready(function(){

 socket=io.connect(window.location.hostname);
    socket.emit('ready'); 

});

  </script>
</html>

请帮我解决这个问题......

2 个答案:

答案 0 :(得分:1)

路由器不是构造函数返回值的方法,它随模块一起导出。

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

同样app.http().io()只需要调用一次,因此将其从路径文件中删除。

答案 1 :(得分:0)

尝试

/* GET home page. */
router.all('/', function(req, res, next) {
    app.io.route('ready', function(res) { //not req.io... 
         console.log('tested..........');
    })
    res.render('index', { title: 'Express' });
});