如何从 node.js 中的 http.request 向浏览器发送响应? [英] how to send the response to browser fromm http.request in node.js?

查看:38
本文介绍了如何从 node.js 中的 http.request 向浏览器发送响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the sample code from nodejs.org and trying to send the response to the browser .

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"); req.end();

但是 req.write("hello") 只是不将字符串输出到浏览器?这不是正确的方法吗?有人还可以告诉我如何将响应输出到 views 文件夹中的 html 以便我可以填充对静态 html 的响应.

But req.write("hello") just does not output the string to the browser ? Is this not the right way ? can someone also tell me how to output the response to the html in views folder so that i can populate the response to the static 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);

此节点脚本将输出保存到文件中:

This node script saves the output to a file:

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

这篇关于如何从 node.js 中的 http.request 向浏览器发送响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆