如何在socket.io事件后重定向客户端? [英] How to redirect a client after a socket.io event?
问题描述
我正在使用node.js及其socket.io模块构建一个简单的登录系统。
我完成了身份验证部分,即使用MongoDB,我现在可以确定尝试登录的用户是真的还是假的。
在这个阶段,当我找到一个真正的登录时,我需要将客户端重定向到另一个页面(index.html)。但是,因为没有发送请求并且不期望使用socket.io事件响应,所以我不能使用
response.setHeader(...);
,因为我的回调函数中没有'response'参数。这是我的代码:
I am building a simple login system using node.js and its socket.io module. I am done with the authentication part, i.e., using MongoDB, I can now ascertain whether the user attempting to log in is genuine or fake. At this stage, when I find a genuine login, I need to redirect the client to a different page (index.html). However, because a request is not sent and a response is not expected with a socket.io event, I cannot use response.setHeader(...); because there is no 'response' parameter in my callback function. Here is my code:
在客户端:
<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
});
});
任何人都可以建议任何方法来做这个吗?
Can anyone please suggest any method to do this?
推荐答案
实现此目的的一种方法是向您的客户端发送重定向事件,并在其末尾处理重定向。
One way of accomplishing this is emitting a redirect event to your client, and handling the redirect on their end.
var destination = '/index.html';
client.emit('redirect', destination);
客户端:
Client-side:
server.on('redirect', function(destination) {
window.location.href = destination;
});
这篇关于如何在socket.io事件后重定向客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!