我正在尝试一起使用路由器和socket.io。
我创建了一个单独的路由器文件,并尝试将路由和socket.io
合并app = require('express.io')();
//var app = express();
//var router = express.Router();
app.http().io();
var mysql = require('mysql');
var connection = mysql.createConnection({
host :'aaaa',
port : 3306,
user : 'bbbb',
password : 'cccc',
database:'dddd'
});
connection.connect(function(err) {
if (err) {
console.error('mysql connection error');
console.error(err);
throw err;
}
});
/* GET home page. */
app.get('/', function(req, res) {
var query = connection.query('select * from xe_livexe_rss limit 0,1',function(err,rows){
console.log(rows);
//res.json(rows);
res.render('index', { title: 'Express',rss:rows });
req.io.route('ready');
});
});
app.io.route('ready', function(req,res) {
req.io.emit('talk', {
message: 'io event from an io route on the server'
});
});
module.exports = app;
但是,当我请求/路由器时,它失败并显示以下消息。
TypeError: Object #<Object> has no method 'emit'
at Object.module.exports [as ready] (/home/ubuntu/nodetest1/routes/index.js:41:12)
at Manager.io.route (/home/ubuntu/nodetest1/node_modules/express.io/compiled/index.js:85:29)
at Object.request.io.route (/home/ubuntu/nodetest1/node_modules/express.io/compiled/index.js:197:29)
at Query._callback (/home/ubuntu/nodetest1/routes/index.js:34:10)
at Query.Sequence.end (/home/ubuntu/nodetest1/node_modules/mysql/lib/protocol/sequences/Sequence.js:78:24)
at Query._handleFinalResultPacket (/home/ubuntu/nodetest1/node_modules/mysql/lib/protocol/sequences/Query.js:143:8)
at Query.EofPacket (/home/ubuntu/nodetest1/node_modules/mysql/lib/protocol/sequences/Query.js:127:8)
at Protocol._parsePacket (/home/ubuntu/nodetest1/node_modules/mysql/lib/protocol/Protocol.js:213:24)
at Parser.write (/home/ubuntu/nodetest1/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/home/ubuntu/nodetest1/node_modules/mysql/lib/protocol/Protocol.js:37:16)
想知道我错过了什么......
答案 0 :(得分:0)
根据您的错误消息,我可以说ready
的回调功能未收到SocketRequest
对象,并且您可以访问RequestIO
对象,该对象包含您正在尝试的事件访问emit(event, data)
。
我猜你的代码有一个如下所示的错误:
/* GET home page. */
app.get('/', function(req, res) {
var query = connection.query('select * from xe_livexe_rss limit 0,1',function(err,rows){
console.log(rows);
//res.json(rows);
res.render('index', { title: 'Express',rss:rows });
req.io.route('ready'); // <==
//When this event is invoked there will be no req/res object passed to your `ready` event.
//This has to be invoked by client script. like
//Emit ready event.
/* `io.emit('ready')`; */ <== clientPage.html
});
});
我有以下代码:
app = require('express.io')();
app.http().io();
// Setup the ready route, and emit talk event.
app.io.route('ready', function(req) {
req.io.emit('talk', {
message: 'io event from an io route on the server'
})
});
// Send the client html.
app.get('/', function(req, res) {
res.sendfile(__dirname + '/client.html')
});
app.listen(7076);