如何在socket.io事件后重定向客户端?

时间:2015-10-24 18:28:12

标签: javascript node.js socket.io

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

在客户端:

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

并在服务器端,

Image

任何人都可以建议任何方法来做到这一点吗?

1 个答案:

答案 0 :(得分:6)

实现此目的的一种方法是向您的客户端发送重定向事件,并在其末端处理重定向。

服务器端:

var destination = '/index.html';
client.emit('redirect', destination);

客户端:

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