2014-11-15 54 views
0

我似乎有一個問題,它似乎完全避開了我。我當前節點的配置是:response.write不能在nodejs上的嵌入式函數中工作

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似乎根本。

任何幫助?

謝謝:)

回答

2

假設res.end()應該是response.end(),你打電話之前response.end()在異步connect回調您res.write電話。

您需要在呼叫進入回調,像這樣:

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(); 
    } 
}); 
+0

先生,你是神。 謝謝! – adalal

相關問題