直接使用
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,
});
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
有点奇怪,但这不是重点。
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