1

I am beginner to Node.js, so as per project requirements I am trying to call REST service from Node.js, I got information of how to call rest from this SO question. Here is the code to make rest call:

var options = {
 host: url,
 port: 80,
 path: '/resource?id=foo&bar=baz',
 method: 'POST'
};

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); //I want to send this 'chunk' as a response to browser
  });
}).end();

The problem is I want to send chunk as a response to a browser, I tried res.write() but it is throwing me error "write method not found". I looked in docs everywhere, but all they give is console.log. Can anyone let me know how can I send that data as a response to a browser?

Community
  • 1
  • 1
Pradeep Simha
  • 17,683
  • 18
  • 56
  • 107
  • 2
    Downvoter: Add an explanatory comment, so that I can correct if "you" feel there is wrong in the question. As I have clearly mentioned I am beginner, you should have a sense to mention whats wrong in this question before downvoting. – Pradeep Simha Aug 12 '13 at 03:51

1 Answers1

1

The callback to http.request is an instance of IncomingMessage, which is a Readable Stream that doesn't have a write method. When making an HTTP request with http.request, you cannot send a response. HTTP is a request-response-message-oriented protocol.

how can I send that data as a response to a browser?

For a browser to be able to get response, it must make a request first. You'll have to have a server running which calls the REST service when it receives a request.

http.createServer(function(req, res) {
  var data = getDataFromREST(function(data) {
    res.write(data);
    res.end();
  });

});
c.P.u1
  • 16,664
  • 6
  • 46
  • 41