我似乎有一个似乎完全无法解决的问题。我当前的节点配置是:
var url = require('url');
var mongoClient = require('mongodb').MongoClient;
var server = require('http').createServer(function(request,response) {
switch (url.parse(request.url).pathname) {
case '/mongotest':
mongoClient.connect('mongodb://localhost:27017', function(err,db) {
if(!err) console.log('Connection successful!');
response.writeHead(200, {'Content-Type':'text/plain'});
response.write('Text to output to browser');
});
break;
case default:
response.writeHead(200, {'Content-Type':'text/plain'});
response.write('Request for ' + url.parse(request.url).pathname + ' received.');
}
res.end();
});
server.listen(8080);
每次我去/ mongotest,控制台都会记录“连接成功!”,但似乎根本没有任何输出在浏览器上,而且writeHead似乎也没有一点都不。
任何帮助?
谢谢:)
答案 0 :(得分:2)
假设res.end()
应该是response.end()
,您需要在response.end()
回拨异步res.write
之前调用connect
。
您需要将该调用移至回调中,如下所示:
var server = require('http').createServer(function(request,response) {
switch (url.parse(request.url).pathname) {
case '/mongotest':
mongoClient.connect('mongodb://localhost:27017', function(err,db) {
if(!err) console.log('Connection successful!');
response.writeHead(200, {'Content-Type':'text/plain'});
response.write('Text to output to browser');
response.end();
});
break;
case default:
response.writeHead(200, {'Content-Type':'text/plain'});
response.write('Request for ' + url.parse(request.url).pathname + ' received.');
response.end();
}
});