I'm trying to get my head around node's connection to mongo via MongoClient. As Far As I Can Tell I'm connecting to Mongo and pulling data and encoding it to JSON. This is not shown in the example bellow as I haven't been able to output the data to the browser while node is still running. I've stripped out everything so as to just present the problem. In code bellow "the connection" is logged to the console but then the browser hangs. If I shut down the node instance then "wtf" is written to the browser window. I'm a node newb so thanks for any help.
var http = require("http");
var MongoClient = require('mongodb').MongoClient;
start();
function start() {
function onRequest(request, res) {
console.log("request");
var mongoclient = MongoClient.connect("mongodb://localhost:27017/first", function(err, db) {
if(!err) {
console.log("the connection");
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("wtf");
res.end;
} else {
console.log(err);
}
});
}
http.createServer(onRequest).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
}
Your code contains a simple typo: res.end should be res.end()
If you don't end the response properly the browser keeps waiting for it to happen (until some timeout happens), which looks like it's hanging. When you stop Node, any pending connections will get closed as part of an internal cleanup, and the browser will get to see the response because of that.