2017-09-28 135 views
0

在我的node.js應用程序中,我想要進行https api調用。我正在嘗試使用https模塊,但它不起作用,但後來我嘗試使用request模塊,這很有效。Https請求在node.js中不起作用

不行

var options = { 
    host : 'myserver/platform-api/v1', 
    port : 80, 
    path : '/projects?access_token=38472', 
    method : 'GET', 
    headers : { 
     'Accept' : 'application/json' 
    } 
}; 
var req = https.request(options, function(res) { 
    res.on('data', function(chunk) { 
     console.log(chunk); 
    }); 
}); 
req.on('error', function(e) { 
    console.log(e); 
    console.log('problem with request:', e.message); 
}); 
req.end(); 

我得到這個

problem with request: getaddrinfo ENOTFOUND myserver/platform-api/v1 
myserver/platform-api/v1:80 

這個作品

request("https://myserver/platform-api/v1/projects?access_token=38472", function(error, response, body) { 
    if (error) return console.log(error); 
    //console.log(error); 
    //console.log(response); 
    console.log(body); 
}); 

我想不通爲什麼它不放在了第一位的工作。有誰知道爲什麼?

感謝

+0

而不是將選項作爲參數傳遞也許傳遞options.path? –

回答

1

編輯交換端口443爲好。您的host似乎包括路徑的一部分?試試這個(左剛纔主持人在host和移動路徑path):

var options = { 
    host : 'myserver', 
    port : 443, 
    path : '/platform-api/v1/projects?access_token=38472', 
    method : 'GET', 
    headers : { 
     'Accept' : 'application/json' 
    } 
}; 
+0

爲什麼你傳遞對象中的所有東西不會將所有這些屬性定義在別處? –

+0

我不確定你在問什麼。 'port'默認爲443,所以可以省略。你是這個意思嗎? – smarx

+0

謝謝,這是港口,我有一部分在主機的路徑。 – omega

2

而且,你打的是80端口,這通常不是HTTPS端口。

+0

好的,謝謝,我想通了,它是端口443,我有部分路徑在主機。 – omega

+0

不客氣。樂意效勞! – theGleep