Illep Illep - 6 months ago 15
Node.js Question

how to call a function from another function - Node JS

I am still new to

Node Js
. Please help me out.

I am calling a web service and based on its results I need to call another web service. The code is given below, however, I am not sure how to call the second web service (ex:
foo()
).

The 2nd method (That calls the 2nd web service) accepts 2 parameter:


  1. Subject

  2. Body



I need to call the web service
'https://somenew.com/v1/'
, and need to pass the following as headers as well :

`Content-Type : application/json`


Then As the body I need to pass the following properties :

"name": "My name is alex",
"gender": ["All"],
"Subject": "french",
"Body": "men",
"arrayOfLikes": {"sf": "tennis"}


// 1st Method

app.post('/createthehospital/',function(req,res){
var hos = req.body;
Hos.create(hos, function(err,hos){
if(err){
// Do nothing
} else {

foo('Subject', 'Body'); // CALLING NEW METHOD
}
}
})
});


// 2nd Method

function foo(subject,body) {
app.post('https://somenew.com/v1/',function(req,res){


});
}

AJS AJS
Answer

You need to use request module

var request = require('request');
request.post({
  url: 'https://somenew.com/v1/',
  headers: {
    'content-type': 'application/json',
  },
  json: {
    "name": "My name is alex",
    "gender": ["All"],
    "Subject": "french",
    "Body": "men",
    "arrayOfLikes": {
      "sf": "tennis"
    }

  }
}, function(error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // your response body 
  }
})

the mistake you have made use express instance app to make call to external url that is not possible use above module to do so.

Comments