大家好,错误是 req.body.user.username 未声明。Req.body.user.username 是用户的用户名,我想在他们聊天时添加 req.body.user.username 作为他们的用户名。
服务器.js
//declarations
var token = require('crypto');
var express = require('express');
var app = express();
var redis = require('redis');
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var client = redis.createClient();
//chat server
server.listen(80);
//confs
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(app.router);
//show redis error in case of error occurs
client.on('error', function (err) {
console.log('Error: ' + client.host + ':' + client.port + ' - ' + err);
});
//chat service
io.sockets.on('connection', function (socket, req) {
socket.on('sendMessage', function (data) {
socket.broadcast.emit('message', data);
socket.emit('message', { text: req.body.user.username + ':' + data.text });
});
});
//route parent directory to index.html
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
//if cookies exist redirect to chat room
app.get('/login/', function (req, res) {
if(req.cookies.login_token) {
res.redirect('/chat/')
} else {
res.sendfile(__dirname + '/login.html');
}
});
//route to register
app.get('/register/', function (req, res) {
res.sendfile(__dirname + '/register.html');
});
//chat
app.get('/chat/', function (req, res) {
if(!req.cookies.login_token) {
res.end('Only registered and logged in users can view this page.');
} else {
res.sendfile(__dirname + '/chat.html');
}
});
//logout
app.get('/logout/', function (req, res) {
if(!req.cookies.login_token) {
res.end('Logged in users only can access this page!');
} else {
res.clearCookie('login_token');
res.end('You has been logged out');
}
});
//login
app.post('/login/', function (req, res) {
client.hmget( req.body.user.username, 'password', function (err,pass) {
if ((!err) && pass && pass == req.body.user.password ) {
require('crypto').randomBytes(48, function(ex, buf) {
var token = buf.toString('hex');
res.cookie('login_token', token);
res.redirect('/chat/');
});
} else if ( pass == false) {
res.redirect('/register/');
} else {
res.redirect('/login/');
}
});
});
//register
app.post('/register/', function (req, res) {
client.hmset(req.body.user.username, 'password',req.body.user.password,
'fname',req.body.user.fname, 'lname', req.body.user.lname,
'password', req.body.user.password, 'email', req.body.user.email,
'mobile', req.body.user.mobile, redis.print);
res.redirect('/login/');
});
那个部分:
io.sockets.on('connection', function (socket, req) {
socket.on('sendMessage', function (data) {
socket.broadcast.emit('message', data);
socket.emit('message', { text: req.body.user.username + ':' + data.text });
});
});
是聊天,但由于错误,我无法显示用户名。谢谢你们的帮助:)