javascript - 在 node.js 中将 rejectUnauthorized 与 node-fetch 一起使用

标签 javascript node.js fetch node-fetch

我目前使用 request 在 node.js 中发出 http 请求。我在某个时候遇到了一个问题,我收到了指示 UNABLE_TO_GET_ISSUER_CERT_LOCALLY 的错误。为了解决这个问题,它设置了rejectUnauthorized。我的请求工作代码如下所示:

    var url = 'someurl';
    var options = {
        url: url,
        port: 443,
        // proxy: process.env.HTTPS_PROXY, -- no need to do this as request honors env vars
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
            'Accept-Language': 'en-us',
            'Content-Language': 'en-us'
        },
        timeout: 0,
        encoding: null,
        rejectUnauthorized: false // added this to prevent the UNABLE_TO_GET_ISSUER_CERT_LOCALLY error
    };
    request(options, function (err, resp, body) {
        if (err) reject(err);
        else resolve(body.toString());
    });


我想我会尝试使用 async/await 切换到 fetch api,现在我正在尝试使用 node-fetch 来做同样的事情。但是,当我做同样的事情时,我又回到了 UNABLE_TO_GET_ISSUER_CERT_LOCALLY 错误。我读到我需要使用代理并尝试使用代理模块,但我仍然没有任何运气。

基于帖子 https://github.com/TooTallNate/node-https-proxy-agent/issues/11我认为以下方法会起作用:
    var options = {
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
            'Accept-Language': 'en-us',
            'Content-Language': 'en-us'
        },
        timeout: 0,
        encoding: null
    };
    var proxyOptions = nodeurl.parse(process.env.HTTPS_PROXY);
    proxyOptions.rejectUnauthorized = false;
    options.agent = new ProxyAgent(proxyOptions);
    const resp = await fetch('someurl', options);
    return await resp.text();

但我仍然得到同样的错误。到目前为止,我能够使用 node-fetch 解决这个问题的唯一方法是在我的环境中设置 NODE_TLS_REJECT_UNAUTHORIZED=0 ,而我真的不想这样做。有人可以帮我看看如何让rejectUnauthorized 与node-fetch 一起工作(大概使用代理,但我真的不在乎只要它被指定为请求的一部分)。

最佳答案

这就是我使用 rejectUnauthorized 使其工作的方式和 Fetch API在 Node.js 应用程序中。
请记住,使用 rejectUnauthorized很危险,因为它会绕过有问题的证书,从而使您面临潜在的安全风险。

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

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

async function getData() {
  const resp = await fetch(
    "https://myexampleapi.com/endpoint",
    {
      agent: httpsAgent,
    },
  )
  const data = await resp.json()
  return data
}

关于javascript - 在 node.js 中将 rejectUnauthorized 与 node-fetch 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60061143/

相关文章:

node.js - 对于博客标签系统,除了在 MongoDB 中嵌套标签数组之外,还有其他方法吗?

node.js - npm 不支持 Node.js v8.17.0

javascript - 有没有办法在 AJAX 调用的 javascript 中或仅在方法中存储 session 变量?

javascript - 为多个应用创建 React App?

javascript - Chrome 阻止了我的地理位置跟踪

reactjs - React 如何制作一个具有固定值和动态值的输入字段

javascript - Backbone.Collection 触发 'reset' 但不是 'add'

javascript - ngrx-默认值被传播运算符覆盖了吗?

javascript - OpenSea 错误 - 请使用 providerUtils.standardizeOrThrow()

php - 从表中更新/删除行(codeigniter)