使用内置 Node.js fetch() 时如何选择性地允许自签名证书?

问题描述 投票:0回答:1

直接使用

node-fetch
https
模块,您可以指定不应拒绝未经授权的HTTPS请求。 例如

const fetch = require('node-fetch');
const https = require('https');

const httpsAgent = new https.Agent({
      rejectUnauthorized: false,
    });

const response = await fetch(url, {
      method: 'POST',
      headers: headers,
      body: body,
      agent: httpsAgent,
    });

但是,如果我使用 Node.js 中已经内置的

fetch
会怎么样?我没有看到任何有关任何特殊“非浏览器”参数的文档。我不想全局禁用 HTTPS 验证,仅针对我在测试特定端点时发出的请求。

我尝试像

agent

一样通过
node-fetch
,但不出所料,这不起作用:

const httpsAgent = new https.Agent({ rejectUnauthorized: false, }); const request = await fetch("https://my_test_api.local/test", { method: "GET", agent: httpsAgent });
结果:

TypeError: fetch failed at node:internal/deps/undici/undici:13178:13 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async file:///home/me/myproject/apitest.js:60:25 { [cause]: Error: self-signed certificate at TLSSocket.onConnectSecure (node:_tls_wrap:1676:34) at TLSSocket.emit (node:events:520:28) at TLSSocket._finishInit (node:_tls_wrap:1087:8) at ssl.onhandshakedone (node:_tls_wrap:873:12) { code: 'DEPTH_ZERO_SELF_SIGNED_CERT' } }
另外,

fetch

这里抛出一个
TypeError
有点奇怪,但这不是重点。

javascript node.js fetch-api self-signed-certificate
1个回答
0
投票
您可以使用环境变量

NODE_EXTRA_CA_CERTS

来传递证书文件。

node --help ... Environment variables: ... NODE_EXTRA_CA_CERTS path to additional CA certificates file. Only read once during process startup.
例如

NODE_EXTRA_CA_CERTS=my-custom-ca.pem


    

© www.soinside.com 2019 - 2024. All rights reserved.