简体   繁体   中英

Nodejs Capture response from API call

I am new to node js. I am trying to call an API that will give me a URL, then I will use this URL to do a number of things like send an SMS, email, insert to mySql DB.

API call is working fine, when I log the URL inside request block (see code commented with WORKING FINE)

But when I try to log the URL outside the request block, it does not work. (See code commented with NOT WORKING FINE). This where I want to do all the things with URL.

Please help. Thanks

 var body = { "mobile": Mobile, "policy": Policy_number, "name": Policy_Holder_Name, "docs": Docs_Pending, "target": 'mobile' }; var options = { uri: BaseURL, method: 'POST', headers: header, json: body }; var URL = ''; request(options, function (error, response, body) { if (!error && response.statusCode == 200) { URL = response.body.url; console.log(URL); //WORKING FINE } }); console.log(URL); //NOT WORKING FINE 

您的要求是asyncronous这就是为什么这件事情正在发生,我建议你使用异步瀑布请参阅本- https://caolan.github.io/async/docs.html#waterfall

As the others state your problem is in the order in which your code executes.

The call to request declares a function on-the-fly (called a lambda function) which will only be executed once the response is received. Execution will then continue through to the end and THEN run that function.

I've commented the code below to try and explain.

/**THIS CODE IS RUN FIRST**/
var body = {
            "mobile": Mobile,
            "policy": Policy_number,
            "name": Policy_Holder_Name,
            "docs": Docs_Pending,
            "target": 'mobile'
            };
var options = {
  uri: BaseURL,
  method: 'POST',
  headers: header,
  json: body
};

var URL = '';

/**DECLARES A FUNCTION BUT IS NOT RUN UNTIL THE REQUEST COMPLETES**/
request(options, function (error, response, body) {
  /**THIS CODE RUNS LAST**/
  if (!error && response.statusCode == 200) {
    URL = response.body.url;
    console.log(URL); //WORKING FINE
  }
});

/**RUNS SECOND - URL IS STILL NOT DEFINED**/
console.log(URL);    //NOT WORKING FINE

If you want some later code to be run, then the best pattern may be to put it in a function.

request(options, function (error, response, body) {
  /**THIS CODE RUNS LAST**/
  if (!error && response.statusCode == 200) {
    doMoreStuff(response.body.url);
  }
});

function doMoreStuff(URL){
  console.log(URL);
}

default value for URL is '' ,

now make http request and if you will get response code 200 , means you successfully got response and URL is not '' ,

Nodejs works asynchronous in nature , so console.log(URL); may be executed before you make http request to api , so it will print ' ' in console.

so it is better to access variable URL inside request's response

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    URL = response.body.url;
    console.log(URL); //WORKING FINE
  }
});

yes you can access URL outside , but you need to wait until your request is completed

for example , wait for 10 second and print URL in console like this :

setTimeout(function(){ console.log(URL)}, 10000);

use AsyncJS for asynchronous operations .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM