在 js 中使用自签名证书发出请求(使用来自 npm 的请求承诺)

Make request with a self-signed cert in js (using request-promise from npm)

我正在使用 request-promise 库发出一个简单的请求,但它出错了,因为我的链中有一个自签名证书(这是一个要求,没有它不是一个选项)

使用 NPM 我可以指定该证书来安装软件包(我已经完成):

npm config set cafile "<path to my certificate file>"

然后我可以安装任何软件包,因为它知道信任我的自签名证书。

有没有办法用 request-promise 发出请求并指定要信任的自签名证书?

请求非常简单:return request.get('/myendpoint')

它只是因为自签名证书而抛出一个错误。

如果 request-promise 无法实现,是否有另一个库支持这种功能?

由于request-promise是对request库的包装(它本身就是对原生http模块的包装),你可以在请求参数中添加如下选项:

const rp = require('request-promise');

const agentOptions = {
  host: 'www.example.com'
, port: '443'
, path: '/'
, rejectUnauthorized: false
};

const agent = new https.Agent(agentOptions);

rp({
  url: "https://www.example.com/api/endpoint",
  method: 'GET',
  agent: agent
}).then(...);

基于 http.request 文档。