2016-12-13 8 views
2

私はajaxを呼び出していくつかの資格情報を取得するノードjsスクリプトを持っています。そのスクリプトの後半でオブジェクトの値を利用する必要があります。アクセスノードのリクエストボディを変数

スクリプト内の別の場所でnewCredentials変数にアクセスする方法がわかりません。

ありがとうございました!

var request = require('request'); 

request('https://localhost/sse/credentials.php', function (error, response, data) { 
if (!error && response.statusCode == 200) { 
    var newCredentials = data; 
} 
else { 
    console.log("Failed to Retrieve Credentials"); 
} 
}); 

//Rest of script here 

答えて

0

メソッドが非同期であるため、結果を同期的にアクセスすることはできません。むしろ結果を返すと、継続またはコールバック関数を使用してプログラムを続行する必要があります。それは、このような単純なものにすることができます

var request = require('request'); 

// Do something with these credentials 
function doSomethingWithCredentials (credentials) { 
    // ... 
} 

request('https://localhost/sse/credentials.php', function (error, response, data) { 
    if (!error && response.statusCode == 200) { 
    // Continue your program with the new data 
    doSomethingWithCredentials(data); 
    } 
    else { 
    console.log("Failed to Retrieve Credentials"); 
    } 
}); 
+0

パーフェクトは - とてもうまくいきました。ありがとうございました!! – Jason

+0

@Jason Glad私は助けることができました! –

関連する問題