I am programming a chat application using socket.io and express 4. Whenever a person login from login.html(client) . Server should remember his name and chat with person online.But in my case it just remember name which has logged in later (Suppose I login from John first and Ron later then it just remembers Ron.). Please Help I am totally new to node.js
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, Twit = require('twit')
, io = require('socket.io').listen(server)
, os = require('os')
, open = require('open')
, bodyParser = require('body-parser')
, mysql = require("mysql");
server.listen(9383,'192.168.1.3');
app.use(bodyParser.urlencoded({ extended: false }));
var name;
app.get('/', function (req, res) {
res.sendfile(__dirname + '/login.html');
});
app.post('/valid', function (req, res) {
console.log("hello");
console.log(req.body.pass);
var username=req.body.email;
var password=req.body.pass;
var connection = mysql.createConnection({
"hostname": "localhost",
"user": "root",
"password": "vk123",
"database": "login"
});
connection.connect();
//Verifying whether person exist if exist it gets its name.
connection.query('SELECT * FROM id WHERE email=? AND password=?', [username,password], function(err, rows){
if (err){
throw err;
}else{
for (var i in rows) {
console.log('name: ', rows[i].name);
name=rows[i].name;
res.redirect('http://192.168.1.3:9383/chat.html');
}
}
});
connection.end();
});
// It is obtaining message from client and sending back message and name.
io.sockets.on('connection', function(socket){
socket.on('chat message', function(msg){
var chatmsg=[];
console.log(name);
console.log(msg);
chatmsg.push({chatname:name, msgtext:msg});
console.log('message: ' +chatmsg[0].chatname);
io.emit('chat message',chatmsg);
});
});
You should have a read on Javascript Variables scope (http://msdn.microsoft.com/en-us/library/ie/bzt2dkta(v=vs.94).aspx).
Your "name" variable is defined as a global variable, that is why it is overwritten.