2017-05-04 15 views
0

所以我有以下場景;我有一個Angular將在XHR請求中顯示的私有API密鑰。爲了解決這個問題,我決定使用Express作爲代理,並提出服務器端請求。但是,我似乎無法找到有關如何製作我自己的獲取請求的文檔。使用Express進行外部獲取請求

架構:

角品牌要求/api/external-api - >快速處理的途徑,使請求externalURL使用參數在req.body.params,重視從config.apiKey API密鑰。以下是僞代碼來模仿我試圖完成的事情:

router.get('/external-api', (req, res) => { 
    externalRestGetRequest(externalURL, req.body.params, config.apiKey) 
    res.send({ /* get response here */}) 
} 
+0

「send get request with nodejs」 –

+1

[Node.js Express中的HTTP GET請求]的可能重複(http://stackoverflow.com/questions/9577611/http-get-request-in-node-js-express ) –

回答

4

你已經走了一半!你需要一些東西來爲你提出這個要求。如npm庫request

在你的路線類似

var request = require('request'); 


router.get('/external-api', function(req, res){ 

request('http://www.google.com', function (error, response, body) { 
     console.log('error:', error); // Print the error if one occurred and handle it 
     console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
     res.send(body) 
    }); 

}) 

這使您可以使用任何你需要的URL或API密鑰的任何類型的請求。但重要的是要注意,您還需要處理任何錯誤或錯誤的響應代碼。

+0

謝謝,這正是我所需要的。用於控制檯日誌記錄的+1。 – Moshe

相關問題