ksh*_*m07 3 javascript node.js socket.io
我正在使用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>
Run Code Online (Sandbox Code Playgroud)
在服务器端,
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
});
});
Run Code Online (Sandbox Code Playgroud)
任何人都可以建议任何方法来做到这一点?
实现此目的的一种方法是向您的客户端发送重定向事件,并在其末端处理重定向.
var destination = '/index.html';
client.emit('redirect', destination);
Run Code Online (Sandbox Code Playgroud)
server.on('redirect', function(destination) {
window.location.href = destination;
});
Run Code Online (Sandbox Code Playgroud)