How to make Ajax request through NodeJS to an endpoint

SharpCoder picture SharpCoder · Jul 23, 2014 · Viewed 40.2k times · Source

I am using NodeJS. One of my function (lets call it funcOne) receives some input which I pass to another function (lets call it funcTwo) which produces some output.

Before I pass the input to funcTwo I need to make an Ajax call to an endpoint passing the input and then I must pass the output produced by the AJAX call to funcTwo. funcTwo should be called only when the AJAX call is successful.

How can I achieve this in NodeJS. I wonder if Q Library can be utilized in this case

Answer

Barış Uşaklı picture Barış Uşaklı · Jul 23, 2014

Using request

function funcOne(input) { 
  var request = require('request');
  request.post(someUrl, {json: true, body: input}, function(err, res, body) {
      if (!err && res.statusCode === 200) {
          funcTwo(body, function(err, output) {
              console.log(err, output);
          });
      }
  });
}

function funcTwo(input, callback) {
    // process input
    callback(null, input);
}

Edit: Since request is now deprecated you can find alternatives here