jeudi 2 avril 2015

Node chat server issues

I have the following node server. The idea was to create a chat server that held chat messages in an array.


It worked fine until I added chat posting, which included both req.on lines and the addMsg function. The server still runs, but if I try to post a message and then refresh the home page it has about 20 posts with the auth and text fields undefined.


Any help is greatly appreciated.



var http = require('http');
var fs = require('fs');
var index = null;
var postpage = fs.readFileSync("post.html");

var chat = [
{auth:"elf", text:"hi"},
{auth:"elf", text:"hello"},
];


fs.readFile('index.html', function(err, data) {
console.log("Server Started");
server.listen(8000);
index = data;
});

var server = http.createServer(function (req, res) {
console.log("Connection Received");
var body = '';
req.on('data', function (chunk) {
console.log("data received")
body += chunk;
});
req.on('end', function () {
if (body != "") {
addMsg(body);
}
res.writeHead(200);
res.end();
});
res.end(router(req.url, res, req));
});

var router = function(url, res, req) {
if (url == "/") {
res.writeHead(200, {'Content-Type': 'text/html'});
console.log("index");
return index;
}
if (url == "/chat") {
res.writeHead(200, {'Content-Type': 'text/html'});
console.log("chat");
return JSON.stringify(chat);
}
if (url == "/post") {
res.writeHead(200, {'Content-Type': 'text/html'});
console.log("post");
return postpage;
}
}

var addMsg = function(body) {
body = body.split('&');
body[0] = body[0].split('=');
body[1] = body[1].split('=');
chat += {auth: body[1], text: body[0]};
};

Aucun commentaire:

Enregistrer un commentaire