如何在 socket.io 事件后重定向客户端? [英] How to redirect a client after a socket.io event?

查看:39
本文介绍了如何在 socket.io 事件后重定向客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node.js 及其 socket.io 模块构建一个简单的登录系统.我已经完成了身份验证部分,即使用 MongoDB,我现在可以确定尝试登录的用户是真还是假.在这个阶段,当我找到一个真正的登录时,我需要将客户端重定向到一个不同的页面(index.html).但是,因为没有发送请求,并且 socket.io 事件没有预期的响应,所以我不能使用response.setHeader(...);因为我的回调函数中没有响应"参数.这是我的代码:

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);

客户端:

server.on('redirect', function(destination) {
    window.location.href = destination;
});

这篇关于如何在 socket.io 事件后重定向客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆