2016-11-27 115 views
0

我有一個NodeJS API。 API中的邏輯需要向google.com發出http獲取請求,捕獲google.com的響應,然後將html響應返回到原始API調用。我的問題是異步捕獲谷歌的http響應並將其返回到原始API調用。NodeJS API使嵌套http獲取請求並返回響應

// Entry point to /api/specialday 
module.exports = function(apiReq, apiRes, apiNext) { 
    var options = { 
    host: 'www.google.com' 
    }; 

    callback = function(googleRes) { 
    var str = ''; 

    // another chunk of data has been recieved, so append it to `str` 
    googleRes.on('data', function (chunk) { 
     str += chunk; 
    }); 

    // capture the google response and relay it to the original api call. 
    googleRes.on('end', function() {   
     apiRes.send(str); 
    }); 
    } 

    http.request(options, callback).end(); 
} 

我在這裏得到的錯誤是Uncaught TypeError: Cannot read property 'send' of undefined。我明白爲什麼我會收到錯誤(因爲apiRes超出範圍),我無法弄清楚如何正確執行。任何幫助非常感謝!

回答

0

您看到上述錯誤的原因是因爲原始響應對象apiRes在您收到來自Google API的響應時已消失。

至於我可以告訴你將不得不bind()apiRes兩次(未經測試):

callback = function(googleRes) { 
    var str = ''; 

    // another chunk of data has been recieved, so append it to `str` 
    googleRes.on('data', function (chunk) { 
    str += chunk; 
    }); 

    // capture the google response and relay it to the original api call. 
    googleRes.on('end', function() {   
    apiRes.send(str); 
    }.bind(apiRes)); 

}.bind(apiRes) 

一個更現代的解決辦法是使用承諾爲這項任務https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

0

承諾,這就是它!謝謝Michal。以下是我的實現的簡化版本。

// Entry point to /api/specialday 
module.exports = function(apiReq, apiRes, apiNext) { 

    var p1 = new Promise(
    // The resolver function is called with the ability to resolve or 
    // reject the promise 
    function(resolve, reject) { 

     var options = { 
     host: 'www.google.com' 
     }; 

     callback = function(googleRes) { 
     var str = ''; 

     // another chunk of data has been recieved, so append it to `str` 
     googleRes.on('data', function (chunk) { 
      str += chunk; 
     }); 

     // capture the google response and relay it to the original api call. 
     googleRes.on('end', function() {   
      resolve(str); 
     }); 
     } 

     http.request(options, callback).end(); 
)}; 

    p1.then(function(googleHtml) { 
    apiRes.status(200).send(googleHtml); 
    } 
} 

然後我可以運行我的應用程序,並調用使用郵差的API在http://localhost:8080/api/gains:使用要求

0

直接與apiRes管輸出,採樣:

var request = require("request"); 

// Entry point to /api/specialday 
module.exports = function(apiReq, apiRes, apiNext) { 
    request.get('http://www.google.fr').pipe(apiRes); 
});