[英]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.