2015-11-22 39 views
0

我試圖訪問一個API,需要我在GET請求的標頭中發送一些信息,如下圖所示。嘗試發送節點中的標頭

enter image description here

我有我的代碼中設置了這樣的,但我發現了一個resp has no method setter錯誤。我已經閱讀過各種文章,並看過其他語言的例子,但是我無法在節點中找到它。

https.get(url, function(resp){ 
        resp.setHeader("Content-Type", "json/application"); 
        resp.setHeader("Authorization", Key); 

        resp.on('data', function(chunk){ 
         sentStr += chunk; 
        }); 

        resp.on('end', function(){ 
         console.log(sentStr); 
        }); 
}); 

回答

1

您正嘗試設置響應的標頭,而請求是需要設置的標頭。 httphttps可以使用URL或一組選項來啓動呼叫。這裏是一個例子

var https = require('https'); 

var options = { 
    hostname: "www.google.com", 
    port: 443, 
    path: '/', 
    method: 'GET', 
    headers: { 
     "Content-Type": "json/application" 
     "Authorization" : "KEY YOU NEED TO SUPPORT" 
    } 
} 

https.get(options, function(res) { 
     console.log("statusCode: ", res.statusCode); 
     console.log("headers: ", res.headers); 

      res.on('data', function(d) { 
        process.stdout.write(d); 
        }); 

}).on('error', function(e) { 
     console.error(e); 
});