Https request not working in node.js

狂风中的少年 提交于 2020-08-10 01:11:27

问题


In my node.js app, I want to make an https api call. I am trying with the https module and it is not working, but then I try with a request module, and that works.

not work

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();

I get this

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

this works

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);
});

I can't figure out why it does not work on the first one. Does anyone know why?

Thanks


回答1:


EDIT Switched to port 443 as well.


Your host seemed to include part of the path? Try this instead (left just the host in host and moved the path to path):

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



回答2:


Also, you're hitting port 80, which is usually not the HTTPS port.



来源:https://stackoverflow.com/questions/46477689/https-request-not-working-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!