/*
Built on example code by Frank Grimm, from http://blog.frankgrimm.net/2010/11/howto-access-http-message-body-post-data-in-node-js/
and MongoDB documentation, from https://docs.mongodb.org/getting-started/node/
Note that all error-checking has been left out, to just focus on learning the basic APIs
*/
var http = require('http');
var querystring = require('querystring');
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';
var formHTML = '
';
var postingHTML = '';
function sendResponse(response, alltext)
{
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('\ntest\n');
response.write('' + formHTML);
response.write('\n');
response.end();
}
function respond(response)
{
var alltext = '';
var cursor = db.collection('chat').find();
cursor.each(function(err,doc) { if (doc != null) { alltext += '' + doc.address + ': ' + doc.text + '' }
else { sendResponse(response,alltext); }
});
}
function processPostData(body,request,response)
{
var postdata = querystring.parse(body);
var d = new Date();
var collection = db.collection('chat');
collection.insertOne({ time : d.toISOString(), address : request.socket.remoteAddress, text : postdata.thetext },
function (err,result) { respond(response); });
}
function message(request, response)
{
var body = '';
request.on('data', function (c) { body += c.toString(); });
request.on('end', function () { processPostData(body,request,response); });
}
function handleRequest(request, response)
{
if (request.method === 'POST')
{
message(request, response);
}
else
{
respond(response);
}
}
var db = null;
function dbConnected(err, database)
{
db = database;
}
MongoClient.connect(url, dbConnected);
http.createServer(handleRequest).listen(8000);