我在页面上有一个按钮,当它被点击时,我希望页面调用一些 node.js 服务器代码。我通过socket.io连接了这个。我遇到的问题是我需要 socket.io 代码根据一些业务逻辑重定向我的网页。不确定通过 express(res.redirect?)实现此目的的最佳方法是什么,以及如何在 socket.io 调用中访问它。任何帮助,将不胜感激!
应用程序.js
var dashboard = require('./middleware/dashboard.js');
...
app.get("/dashboard", function (req, res) {
dashboard.show(req, res);
});
...
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.set('log level',2); // sets socket io log level 0=error, 1=warn, 2=info, 3=debug
...
dashboard.wireUpSocketIO(io);
...
仪表板.js
var savedResponse;
exports.show = function(req, res) {
savedResponse = res;
res.render("dashboard.jade"});
};
exports.wireUpSocketIO = function(io){
io.sockets.on('connection', function (socket) {
socket.on('dashboardOnButtonClick', function(msg) {
<biz logic>
savedResponse.render("someOtherPage.jade", {
locals: {
title: "someOtherPage",
filter: msg.filter
}
});
});
});
}
仪表板.jade
button#btnFilter(class='btn btn-info') Test Button
script(src="/socket.io/socket.io.js")
script .
var socket = io.connect('http://localhost');
var emitMessage = { blah: false, filter:"n/a"};
$('#btnFilter').click(function(){
emitMessage.blah = true;
emitMessage.filter = "filterByBlah";
socket.emit('dashboardOnButtonClick', emitMessage);
});