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?

1
  • 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. Commented Aug 12, 2013 at 3:51

1 Answer 1

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

});
Sign up to request clarification or add additional context in comments.

Comments

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.