首页 > 解决方案 > 在 js 中使用自签名证书发出请求(使用来自 npm 的 request-promise)

问题描述

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

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

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

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

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

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

由于自签名证书,它只会引发错误。

如果不可能,request-promise是否有另一个库允许这种功能?

标签: javascriptnode.jssslrequest-promiseself-signed-certificate

解决方案


由于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文档。


推荐阅读