I am developing basic application that has a simple membership. Besides, i need to develop Sessions aswell. In my following code, sockets do not respond. Can you help me to find the reason behind that ?
app.js
var WebApp = require('./webApp.js');
var db = require('./db/db.js');
var db = new db();
var webApp = new WebApp();
var App = function(){}
webApp.initialize();
webApp.socketIOConnect(function(client){
webApp.socketIOConnectMethods(client);
});
module.exports = App;

webApp.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var router = express.Router();
var path = require('path');
var Db = require('./db/db.js');
var connect = require('connect');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var socketHandshake = require('socket.io-handshake');
var io = require('socket.io')(server);
io.use(socketHandshake({secret:'secret',resave : false, saveUninitialized : true, parser:cookieParser()}));
server.listen(1185);
var WebApp = function () {
console.log("Greetings from WebApp Module.");
}
var db = new Db();
WebApp.prototype.initialize = function () {
app.use(express.static("./assets"));
router.get('/', function (req, res, next) {
res.sendFile("./assets/index.html");
});
router.get('/login', function (req, res, next) {
res.sendFile(path.resolve("./assets/login.html"));
});
router.get('/client', function (req, res, next) {
res.sendFile(path.resolve("./client/client.html"));
});
app.use(router);
}
WebApp.prototype.socketIOConnect = function(callback) {
io.on('connection', function(client, req, res) {
callback(client)
});
}
WebApp.prototype.socketIOConnectMethods = function (client) {
if (client.handshake.session.name) {
console.log('We already know you!');
client.emit('get name');
client.emit('redirect');
};
client.on('join', function(data) {
console.log(data);
});
client.on('register', function(data) {
client.emit('username', data);
console.log(data);
var checkAuth;
var username = data.user;
var password = data.passw;
var email = data.email;
var confpass = data.confirmPass;
console.log("password : "+password);
console.log("conf password :"+confpass);
if ( password == confpass){
console.log("Passwords match, this lad can login");
var values = [[, username, password, email]];
console.log(username + " " + password + " " + email);
db.registAuth(email,function(err, results) {
if (err) {
console.log("An error occurred: " + err.message);
}
client.on('passwordmatches',function(data){
console.log(data);
});
console.log(results);
var checkAuth = results.length;
if(results < 1){
db.userRegistration(values,function(err, results) {
if(err) {
console.log("An error occurred: " + err.message);
}
console.log(results);
});//user registration
}
else{console.log("Sorry, we could not complete your registration. Email already exists.");}
});//registAuth
}
else{
client.on('NoMatchPass',function(data){
console.log(data);
});
console.log("Sorry, we could not complete your registration. Passwords do not match !");
client.emit('tryagainreg',"Sorry, we could not complete your registration. Passwords do not match !");
}
});//client.on register
client.on('login', function(data) {
var email = data.email;
var password = data.password;
console.log(data);
db.loginAuth(email, password, function(err, results) {
if (err) {
console.log("An error occurred: " + err.message);
}
console.log(results.length);
if ( results.length == 1){
console.log("Welcome, "+email+"!");
client.handhsake.session.name = email;
client.handshake.session.save();
console.log(client.handshake.session.name);
client.emit('AuthLogin',email);
}
else{console.log("Wrong username or password.");
client.emit('FailedLogin',email);
}
});
});
};
module.exports = WebApp;
&#13;
我希望用户在成功完成注册后登录,然后,当他们成功登录时,我想将它们重定向到client.html但是使用会话,以便我可以保留他们的授权,直到他们退出应用程序。
的login.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">
<link rel="icon" type="image/png" href="../assets/img/favicon.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Let's Get Head In</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<!-- Fonts and icons -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
<!-- CSS Files -->
<link href="./css/bootstrap.min.css" rel="stylesheet" />
<link href="./css/material-kit.css" rel="stylesheet"/>
</head>
<body class="signup-page">
<nav class="navbar navbar-transparent navbar-absolute">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navigation-example">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="">AslanServices</a>
</div>
<div class="collapse navbar-collapse" id="navigation-example">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="./index.html" target="">
Register
</a>
</li>
<li>
<a href="" target="">
<i class="material-icons">unarchive</i>Contact
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="wrapper">
<div class="header header-filter" style="background-image: url('./img/city.jpg'); background-size: cover; background-position: top center;">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
<div class="card card-signup">
<form class="loginform" method="" action="">
<div class="header header-primary text-center">
<h4>Sign In</h4>
</div>
<div class="content">
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">email</i>
</span>
<input type="text" class="form-control" id="email" placeholder="Email...">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">lock_outline</i>
</span>
<input type="password" placeholder="Password..." id="password" class="form-control" />
</div>
<!-- If you want to add a checkbox to this form, uncomment this code
<div class="checkbox">
<label>
<input type="checkbox" name="optionsCheckboxes" checked>
Subscribe to newsletter
</label>
</div> -->
</div>
<div class="footer text-center">
<button type="submit" class="btn" value="Submit">Sign in!</button>
</div>
</form>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<nav class="pull-left">
<ul>
<li>
<a href="https://www.instagram.com/ozercevikaslan/">
AslanServices
</a>
</li>
<li>
<a href="https://www.instagram.com/ozercevikaslan/">
About Us
</a>
</li>
</ul>
</nav>
<div class="copyright pull-right">
© 2017, made by <a href="https://www.instagram.com/ozercevikaslan/" target="_blank">Aslanmeister</a>
</div>
</div>
</footer>
</div>
</div>
</body>
<!-- Core JS Files -->
<script src="./js/jquery.min.js" type="text/javascript"></script>
<script src="./js/bootstrap.min.js" type="text/javascript"></script>
<script src="./js/material.min.js"></script>
<!-- Plugin for the Sliders, full documentation here: http://refreshless.com/nouislider/ -->
<script src="./js/nouislider.min.js" type="text/javascript"></script>
<!-- Plugin for the Datepicker, full documentation here: http://www.eyecon.ro/bootstrap-datepicker/ -->
<script src="./js/bootstrap-datepicker.js" type="text/javascript"></script>
<!-- Control Center for Material Kit: activating the ripples, parallax effects, scripts from the example pages etc -->
<script src="./js/material-kit.js" type="text/javascript"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('127.0.0.1:1185');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
socket.on('redirect',function(callback){ callback(window.location.href="127.0.0.1:1185/client");
});
$('form.loginform').submit(function(event){
event.preventDefault();
var email = $('#email').val();
var password = $('#password').val();
socket.emit('login',{email : email, password : password});
socket.on('AuthLogin',function(data){window.location.href = 127.0.0.1:1185/client";});
socket.on('FailedLogin',function(data){alert('Wrong username or Password. Maybe, you dont even exist!');window.location.href = "127.0.0.1:1185";});
});
});
</script>
</html>
&#13;
答案 0 :(得分:0)
我只是使用下面的代码解决了我的问题。
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var router = express.Router();
var path = require('path');
var Db = require('./db/db.js');
var connect = require('connect');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.use(cookieParser('aslan'));
var redis = require("redis");
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var io = require('socket.io')(server);
var cookie = require('cookie');
//var passwordHash = require('password-hash');
var redisclient = redis.createClient();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true }));
var sessionMiddleware = session({
store: new RedisStore({host : 'localhost' , port : '6379' , client : redisclient , ttl : 15}), // redis server config
secret: 'aslan',
resave : false,
saveUninitialized : false
});
app.use(sessionMiddleware);
//---------------CONFIG PART ENDED-------------
app.get('/',function (req, res, next) {
session = req.session;
if ( session.key ){
res.redirect('/'+session.key+'');
}
res.sendFile("./assets/index.html");
});
//---------------------------------
app.get('/login', function (req,res,next) {
session = req.session;
if ( session.key ){
if ( session.key == 'admin@gmail.com'){res.redirect('/admin');}
if ( session.key != 'admin@gmail.com'){res.redirect('/'+session.key);}
}
res.sendFile(path.resolve("./assets/login.html"));
});
//--------------------------------LOGIN POST------------------
app.post('/login', function (req,res,next) {
console.log("hi from login post");
var email = req.body.user.email;
var password = req.body.user.password;
db.loginAuth(email, password, function(err, results) {
if (err) {
console.log("An error occurred: " + err.message);
}
console.log(results.length);
if ( results.length == 1){
console.log("Welcome, "+email+"!");
//session
session = req.session;
session.key = email;
db.returnUsername(session.key,function(err,result){
if (err) {
console.log('An Error Occured in Db :' + err.message);
}
console.log(result);
console.log(session.key+'Before checking');
if ( session.key == 'admin@gmail.com'){console.log('Session key is equal to admin@gmail.com'); res.redirect('/admin');}
if ( session.key != 'admin@gmail.com'){console.log('Session key is not equal to admin@gmail.com'); res.redirect('/evsahibi');}
});
}
else{console.log("Wrong username or password.");}
});
});
&#13;