Node Script have to call a URL , and get the response and use the some variable of the response to call the next url. is it possible?
in below example, i'm using token in other scripts.
var http = require('http');
var options = {
host: 'url' ,
path: '/path',
method: 'POST'
};
var req = http.request(options, function(res) {
token="hi"; // to be populated by res
});
req.end();
exports.token = token
I think you're trying to export token
before it exists. When you assign token = "hi"
, that happens after the http request finishes and you get the response. What you want to do instead is export
a function with a callback which returns your data from the url.
var http = require('http');
var options = {
host: 'url' ,
path: '/path',
method: 'POST'
};
exports.getToken = function (callback) {
http.request(options, function(res) {
callback(res);
});
};
Then in your other module, you would have to call the getToken
function passing it a callback function.
//I assume the above file is called tokenFinder.js
var tokenFinder = require('./tokenFinder');
var token;
tokenFinder.getToken(function (data) {
token = data;
});