【问题标题】:how to send the response to browser fromm http.request in node.js?如何从 node.js 中的 http.request 向浏览器发送响应?
【发布时间】:2011-11-06 11:18:09
【问题描述】:

我正在使用来自 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") 只是不将字符串输出到浏览器吗? 这不是正确的方法吗?谁能告诉我如何在views文件夹中输出对html的响应,以便我可以填充对静态html的响应。

【问题讨论】:

    标签: javascript web-applications node.js


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 非常感谢。只是另一个问题。你知道如何在views文件夹中的.htm中显示数据(在这种情况下是块)。
    • 添加了将输出保存到文件的脚本
    猜你喜欢
    • 2013-08-13
    • 2020-04-07
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多