How to make remote REST call inside Node.js? any CURL?

In Node.js, other than using child process to make CURL call, is there a way to make CURL call to remote server REST API and get the return data?

I also need to set up the request header to the remote REST call, and also query string as well in GET (or POST).

I find this one: http://blog.nodejitsu.com/jsdom-jquery-in-5-lines-on-nodejs

but it doesn't show any way to POST query string.


Look at http.request

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

How about using Request — Simplified HTTP client.

Edit February 2020: Request has been deprecated so you probably shouldn't use it any more.

Here's a GET:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode === 200) {
        console.log(body) // Print the google web page.
     }
})

OP also wanted a POST:

request.post('http://service.com/upload', {form:{key:'value'}})

I use node-fetch because it uses the familiar (if you are a web developer) fetch() API. fetch() is the new way to make arbitrary HTTP requests from the browser.

Yes I know this is a node js question, but don't we want to reduce the number of API's developers have to memorize and understand, and improve re-useability of our javascript code? Fetch is a standard so how about we converge on that?

The other nice thing about fetch() is that it returns a javascript Promise, so you can write async code like this:

let fetch = require('node-fetch');

fetch('http://localhost', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{}'
}).then(response => {
  return response.json();
}).catch(err => {console.log(err);});

Fetch superseeds XMLHTTPRequest. Here's some more info.