如何发送响应浏览器fromm http.request node.js?

我正在使用来自nodejs.org的示例代码并尝试将响应发送到浏览器。

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( “你好”); req.end();

但req.write(“你好”)只是不会输出到浏览器的string? 这不正确吗? 有人也可以告诉我如何输出到视图文件夹中的HTML响应,以便我可以填充对静态HTML的响应。

尝试这个:

 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();