2

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

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 .

1 Answer 1

2

Try this:

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

Edit:

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot .just another question . Do you know how to display the data (chunk in this case ) in .htm within views folder.
Added a script which saves the output to a file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.