-1
我在頁面上有一個按鈕,當它被點擊時,我希望頁面調用一些node.js服務器代碼。我通過socket.io連接了這個接口。我遇到的問題是我需要socket.io代碼來重定向我的網頁基於一些業務邏輯。不知道通過express(res.redirect?)來做到這一點的最好方法是什麼,以及如何在socket.io調用中訪問它。任何幫助,將不勝感激!node.js在socket.io中快速路由到一個新頁面
App.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);
...
dashboard.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
}
});
});
});
}
dashboard.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);
});
那是安全的,當網絡渲染客戶端新的一頁? – Kramer
@KammerLee我不是爲什麼它不應該,也許你想詳細說明你的擔憂? – Hugo