首页 > 解决方案 > 如何在 uri 中使用 https 模块?

问题描述

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

下面的代码示例适用于 request-promise-native 库

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 模块执行此请求吗?

标签: node.jshttpsrequest-promise

解决方案


推荐阅读