我正在使用socket.io和express编写聊天应用程序4.每当有人从login.html(客户端)登录时。服务器应该记住他的名字,并在线与人聊天。但在我的情况下,它只记得以后登录的名字(假设我先从John登录,然后罗恩再次记住罗恩。)。请帮助我对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);
});
});
答案 0 :(得分:0)
您应该阅读Javascript变量范围(http://msdn.microsoft.com/en-us/library/ie/bzt2dkta(v=vs.94).aspx)。
您的“名称”变量被定义为全局变量,这就是它被覆盖的原因。