[英]Working with express.io in a separate router file
我正在嘗試一起使用router和socket.io。
我創建了一個單獨的路由器文件,並嘗試將route和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)
只是想知道我錯過了什么...
根據您的錯誤消息,我可以說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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.