2016-11-17 153 views
0

我試圖對API執行GET請求,並將API響應中的數據返回給客戶端。我認爲客戶端在API完成GET請求之前收到響應。如何更改代碼以確保API的響應傳遞給客戶端?使用響應鏈接GET請求Node.js

if (request.method == 'POST' && request.url == '/locationdata') { 
    var body = ''; 
    request.on('data', function (data) { 
     body += data; 
    }); 

    request.on('end', function() { 
     var formattedLocation = body.replace(/[\[\]']+/g, ''); 
     var urlAPI = 'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/' + formattedLocation; 

     response.writeHead(200, { 'Content-Type': 'application/json' }); 
     var apiData = ''; 

     var apirequest = function() { 
      https.get(urlAPI, function (response) { 
       response.on('data', function (data) { 
        apiData += data; 
       }); 
       response.on('end', function() { 
        console.log(apiData); 
        return apiData; 
       }); 
      }); 
     } 

     response.end(apirequest); 
    }); 

    return; 
} 

回答

1

在從api獲取所有數據之前,您將結束對客戶端的響應。移動response.end()調用到api響應結束時應該修復它:

if (request.method == 'POST' && request.url == '/locationdata') { 
    var body = ''; 
    request.on('data', function (data) { 
     body += data; 
    }); 

    request.on('end', function() { 
     var formattedLocation = body.replace(/[\[\]']+/g, ''); 
     var urlAPI = 'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/' + formattedLocation; 

     response.writeHead(200, { 'Content-Type': 'application/json' }); 
     var apiData = ''; 

     https.get(urlAPI, function (apiResponse) { 
      apiResponse.on('data', function (data) { 
       apiData += data; 
      }); 
      apiResponse.on('end', function() { 
       console.log(apiData); 
       // send response to browser after we get all the data from the api 
       response.end(apiData); 
      }); 
     }); 

     // remove this because we moved it up 
     //response.end(apirequest); 
    }); 

    return; 
} 
+0

我仍然收到一個錯誤。我在節點中獲取API數據,但我認爲在響應結束之前它仍未被髮送到瀏覽器。我在瀏覽器中出現以下錯誤:'「語法錯誤:JSON.parse ...」' –

+0

我調整了答案並在代碼中包含了它的完整副本 – Ryan

+0

它的工作原理!謝謝。你的調整隻是一個小錯誤。我必須改變'response.end(apirequest);''response.end(apiData);' –