在封闭方法中访问Node JS Express请求中的POST响应数据

时间:2017-02-09 04:10:37

标签: node.js express callback request

我正在抨击Node JS学习曲线。我在Node JS Express中有一个应用程序使用请求对另一个API进行POST。通话很顺利,我的控制台日志显示正确的数据返回。我的问题是如何从request.post(...)中获取响应,并在发出请求的方法中使用它。

这是我的情景。外部应用程序调用我的API。我的API必须调用另一个API来获取一些数据来检查更新。 (我有一个API发出POST请求,以响应来自外部应用程序的POST请求。)

这是我的API中的方法,它向第三方请求某些数据。我需要从这个POST响应中获取数据,在我对外部应用程序的POST请求的响应中返回之前对它做一些事情。

exports.getUpdates = function(variable1, variable2, variable3) {
     request.post(
        'http://myurl.exp/api//getUpdates',
        {json: {var1: variable1, ...}},
        function (error, response, body) {
           if(!error && response.statusCode == 200) {
             console.log(body);
           } else {console.log(error);}
        }
     );
  <I need to have this method return the response to the controller that called this method>
 };

我已经看过很多例子,但是他们都只是说console.log(),我正在变得讨厌。我猜它与回调有关,我怎么没有正确处理它,但是我的研究都没有给我一个明确的方法 处理回调。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

利用回调

exports.getUpdates = function(variable1, variable2, variable3, callback) {
     request.post(
        'http://myurl.exp/api//getUpdates',
        {json: {var1: variable1, ...}},
        function (error, response, body) {
           if(!error && response.statusCode == 200) {
             callback(error, response, body);
           } else {console.log(error);}
        }
     );
 };

现在,您可以在调用此函数时传递回调:

getUpdates(var1, var2, var3, function(error, response, body) {
    //stuff that you want to perform after you get response or error
});

但是,我建议采用更简洁的方法:

exports.getUpdates = function(variable1, variable2, variable3, callback) {
     request.post('http://myurl.exp/api//getUpdates', 
                     {json: {var1: variable1, ...}}, callback);
 };

现在,您可以在调用此函数时传递回调:

getUpdates(var1, var2, var3, function(error, response, body) {
        if(!error && response.statusCode == 200) {
            // stuff you want to do
        } else {
            console.log(error);
        }
    }
});