cURL equivalent in Node.js?

I'm looking to use information from an HTTP request using Node.js (i.e. call a remote web service and echo the response to the client).

In PHP I would have used cURL to do this. What is the best practice in Node?


Solution 1:

See the documentation for the HTTP module for a full example:

https://nodejs.org/api/http.html#http_http_request_options_callback

Solution 2:

The http module that you use to run servers is also used to make remote requests.

Here's the example in their docs:

var http = require("http");

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

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

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();