Making a REST call from Node.js and sending a response to the browser

I start with Node.js, so, according to the requirements of the project, I try to call the REST service from Node.js, I got information on how to call peace from this SO question . Here is the code to call the rest:

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 that I want to send chunk as a response to the browser, I tried res.write() , but it throws me an error "write method not found". I looked in the docs everywhere, but all they give is console.log. Can someone tell me how can I send this data in response to the browser?

+1
source share
1 answer

The http.request is an instance of IncomingMessage , which is a Readable stream that does not 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 this data in response to the browser?

In order for the browser to receive a response, it must make the request first. You will need to start the server, which calls the REST service when it receives the request.

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

Source: https://habr.com/ru/post/1275688/


All Articles