-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
96 lines (66 loc) · 4.51 KB
/
app.js
1
// Retrievevar MongoClient = require('mongodb').MongoClient;var http = require('http');const PORT = 8080;var server = http.createServer(handlerRequest);server.listen(PORT, function(){ console.log('Server is started and listening on: ' + PORT); });var dispatcher = require('httpdispatcher')function handlerRequest(req, res) { try { console.log(req.url); dispatcher.dispatch(req, res); } catch(err) { console.log(err) }}dispatcher.setStatic('resources');dispatcher.onGet("/page1", function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Page One') });dispatcher.onPost('/post1', function(req, res) { res.writeHead(200, {'Content-Type':'text/plain'}); res.end('Got Post Data') });dispatcher.onGet('/page2', function(req, res) { res.writeHead(200, {'Content-Type': 'application/json'}); // Connect to the db MongoClient.connect("mongodb://localhost:27017/test", function(err, db) { if(!err) { console.log("We are connected"); db.collection('cars', function(err, collection) { collection.find().toArray(function(err, items){ console.log(items); var json = JSON.stringify(items); res.end(json); db.close() }); }); } else { console.log("connect fail") res.end("fail") } }); });dispatcher.onGet('/insert', function(req, res) { res.writeHead(200, {'Content-Type': 'application/json'}); // Connect to the db MongoClient.connect("mongodb://localhost:27017/test", function(err, db) { if(!err) { console.log("We are connected"); db.collection('cars', function(err, collection) { collection.find().toArray(function(err, items){ console.log(items); var json = JSON.stringify(items); res.end(json); db.close() }); }); } else { console.log("connect fail") res.end("fail") } }); });