![](/img/trans.png)
[英]How to redirect the client when socket gets disconnected in socket.io?
[英]How to redirect a client after a socket.io event?
我正在使用node.js及其socket.io模塊構建一個簡單的登錄系統。 我完成了身份驗證部分,即使用MongoDB,我現在可以確定嘗試登錄的用戶是真的還是假的。 在此階段,當我找到正版登錄時,我需要將客戶端重定向到不同的頁面(index.html)。 但是,因為沒有發送請求並且不期望使用socket.io事件響應,所以我不能使用response.setHeader(...); 因為我的回調函數中沒有'response'參數。 這是我的代碼:
在客戶端:
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket=io();
$('form').submit(function(){
var un=$('#un').val();
var pw=$('#pw').val();
socket.emit('login',un,pw);
return false;
});
</script>
在服務器端,
var app=require('express')();
var server=require('http').Server(app);
var io=socket(server);
io.on('connection',function(client){
client.on('login',function(username,pw){
//if authenticated, direct the client to index.html
});
});
任何人都可以建議任何方法來做到這一點?
實現此目的的一種方法是向您的客戶端發送重定向事件,並在其末端處理重定向。
var destination = '/index.html';
client.emit('redirect', destination);
server.on('redirect', function(destination) {
window.location.href = destination;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.