如何从node.js中的http.request发送响应到浏览器?

时间:2011-08-30 02:14:03

标签: javascript web-applications 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(“hello”)只是不将字符串输出到浏览器? 这不是正确的方法吗?有人还可以告诉我如何输出对视图文件夹中的html的响应,以便我可以填充静态html的响应。

1 个答案:

答案 0 :(得分: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();