如何在uri中使用https模块?

时间:2018-10-05 11:48:44

标签: node.js https request-promise

我正在尝试在nodejs中使用本机https模块。

下面的代码示例可以与请求-承诺-本地库一起正常工作

var apiver = '2017-09-01';
var resource = 'https://management.azure.com/';
const rp = require('request-promise-native');
var options = {
    uri: `${process.env["MSI_ENDPOINT"]}/?resource=${resource}&api-version=${apiver}`,
    headers: {
        'Secret': process.env["MSI_SECRET"]
    }
};
return rp(options);

此处uri =“ http://127.0.0.1:41437/MSI/token//?resource=https://management.azure.com/&api-version=2017-09-01

但是,如果我尝试使用https模块执行相同的操作,则会引发错误

return new Promise( (resolve,reject) => {
    var apiver = '2017-09-01';
    var resource = 'https://management.azure.com/';
    var options = {
        "method": "GET",
        "hostname": "localhost",
        "port": 41437,
        "protocol": "https:",
        "path": `/MSI/token/?resource=${resource}&api-version=${apiver}`,
        headers: {
            'Secret': process.env["MSI_SECRET"]
        }
    };
    var req = https.request(options, function (res) {
        var body = '';
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            body += chunk;
        });
        res.on('end', function () {
            if (res.statusCode == 200) {
                resolve(body);
            } else {
                reject({'error':null,'res':res});
            }
        });
    });
    req.on('error', function (e) {
        reject({'error':e,'res':null});
    });
    req.end();
});

引发以下错误

{ 
    hostname: 'localhost',
    port: 41437,
    protocol: 'https:',
    path: '/MSI/token/?resource=https://management.azure.com/&api-version=2017-09-01',
    headers: { Secret: '41A1BDD07D4B42159F71353FCCE2F0EB' } }
    2018-10-05T11:36:12.395 [Info] { error: {    
        Error: connect EACCES 127.0.0.1:41437
          at Object.exports._errnoException (util.js:1020:11)
          at exports._exceptionWithHostPort (util.js:1043:20)
          at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
        code: 'EACCES',
        errno: 'EACCES',
        syscall: 'connect',
        address: '127.0.0.1',
        port: 41437 
    },
    res: null 
}

是否可以通过本机https模块执行此请求?

0 个答案:

没有答案