Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Ajax request through NodeJS to an endpoint

Tags:

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

like image 329
SharpCoder Avatar asked Jul 23 '14 13:07

SharpCoder


People also ask

How send AJAX data to Nodejs?

You will need to install this dependency with npm install --save body-parser . Then you need to send a POST request to that URL from the front-end. $. ajax({ type: "POST", url: "/mail", data: { mail: mail }, success: function(data) { console.

Can you use AJAX in node JS?

This can be done by Ajax request, we are sending data to our node server, and it also gives back data in response to our Ajax request. Step 1: Initialize the node modules and create the package. json file using the following command.


1 Answers

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

like image 127
Barış Uşaklı Avatar answered Oct 11 '22 16:10

Barış Uşaklı