2011-08-30 50 views
2

我正在使用來自nodejs.org的示例代碼並嘗試將響應發送到瀏覽器。 (「hello」);如何發送響應瀏覽器fromm http.request node.js?

var http = require("http"); 
var port = 8001; 
http.createServer().listen(port); 
var options = { 
    host: "xxx", 
    port: 5984, 
    //path: "/_all_dbs", 
    path: "xxxxx", 
    method: "GET" 
}; 

var req = http.request(options, function(res) { 
    console.log('STATUS: ' + res.statusCode); 
    console.log('HEADERS: ' + JSON.stringify(res.headers)); 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
    console.log('BODY: ' + chunk); 
     var buffer = ""; 
     buffer += chunk; 
     var parsedData = JSON.parse(buffer); 
     console.log(parsedData); 
     console.log("Name of the contact "+parsedData.name); 
    }); 
}); 

req.on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
}); 

req.write(「hello」); req.end();

但req.write(「hello」)只是不會輸出字符串到瀏覽器? 這不正確嗎?有人也可以告訴我如何輸出響應到視圖文件夾中的HTML,以便我可以填充對靜態html的響應。

回答

2

試試這個:

var http = require('http'); 

var options = { 
    host: "127.0.0.1", 
    port: 5984, 
    path: "/_all_dbs", 
    method: "GET" 
}; 

http.createServer(function(req,res){ 
    var rq = http.request(options, function(rs) { 
     rs.on('data', function (chunk) { 
      res.write(chunk); 
     }); 
     rs.on('end', function() { 
      res.end(); 
     }); 
    }); 
    rq.end(); 
}).listen(8001); 

編輯:

此節點腳本保存輸出到文件:

var http = require('http'); 
var fs=require('fs'); 

var options = { 
    host: "127.0.0.1", 
    port: 5984, 
    path: "/_all_dbs", 
    method: "GET" 
}; 
var buffer=""; 
var rq = http.request(options, function(rs) { 
    rs.on('data', function (chunk) { 
     buffer+=chunk; 
    }); 
    rs.on('end', function() { 
     fs.writeFile('/path/to/viewsfolder/your.html',buffer,function(err){ 
      if (err) throw err; 
      console.log('It\'s saved!');    
     }); 
    }); 
}); 
rq.end(); 
+0

非常感謝。只是另一個問題。你知道如何在視圖文件夾中的.htm中顯示數據(在這種情況下是塊)。 – Preethi

+0

添加了一個將輸出保存到文件的腳本 – stewe

相關問題