0

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/');
}
4

1 回答 1

1

您的代码包含一个简单的错字:res.end应该是res.end()

如果您没有正确结束响应,浏览器会一直等待它发生(直到发生一些超时),这看起来像是挂起。当您停止 Node 时,任何挂起的连接都将作为内部清理的一部分关闭,因此浏览器将看到响应。

于 2013-05-12T07:41:40.960 回答