回调函数不会从我的HTTP POST调用中检索结果

时间:2018-01-27 03:30:48

标签: javascript node.js rest variables

我想进行 REST调用并将结果输出到变量 access_token )。我的变量AFAIK是全球性的。为什么我的变量access_token在结尾处未定义,即使我在控制台中得到了结果?我知道这个电话是异步的,但是我提出了一个假的错误。在电话中。

var https = require('https'),
querystring = require('querystring');

require('request-to-curl');
// First, get access token

var postData = querystring.stringify({
    'grant_type': 'password',
    'username':'<myusername>',
    'password':'<mypassword>'
});

var options = {
    hostname: 'myserver.com',
    port: 443,
    path: '/v1/oauth2/token',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': postData.length
    }
};
    function postVal(options, value) {
 //var responseObject;
 var access_token;

    var responseObject;
    var req = https.request(options, function(res) 
    {
      res.setEncoding('utf-8');

      var responseString = '';

      res.on('data', function(data) {
        responseString += data;
      });

      res.on('end', function() {
        console.log(responseString);
        responseObject = (JSON.parse(responseString));
       access_token = responseObject.access_token;
        console.log('console access:' + access_token);
        value(access_token);
       // return responseObject;
      });
    });
    req.on('error', (e) => {
        console.log(`problem with request: ${e.message}`);
      });
      // write data to request body 
    req.write(postData);
    req.end();
}


 console.log("Access:"+ postVal(options, function(access) {
     console.log(access);
 }));

结果

 $ node curl.js
    Access:undefined
    {"token_type":"Bearer","access_token":"f3DzDqW..dbMo0","refresh_token":"4jXqo4..kuuc2rMux3","scope":"global","access_token_type":"USER_GENERATED","note":"","expires_in":900}
    console access:f3DzDqWpnrgxnxt5vE42ih8ew..gOKyJY5dbMo0
    mlieber-ltm12:

0 个答案:

没有答案