如何在节点中使用 fetch 发出 http 请求?节点获取

jha*_*amm 4 fetch node.js

我正在尝试在节点中发出请求。这是我的代码:

fetch("http://www.test.com", options).catch(err => {
    console.error(err);

    return err;
  });
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误。 TypeError: Only HTTP(S) protocols are supported

我尝试创建一个新代理并将其传递到如下选项中:

const httpAgent = new http.Agent({
    keepAlive: true
});
const httpsAgent = new https.Agent({
    keepAlive: true
});

const options = {
    agent: function (_parsedURL) {
        if (_parsedURL.protocol == 'http:') {
            return httpAgent;
        } else {
            return httpsAgent;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我仍然遇到同样的错误。

当我在客户端中运行它时,我可以向客户端发送一个http或一个请求,并且没有问题。显然它在节点上是不同的。httpsfetch

处理这个问题的最佳方法是什么?

小智 7

检查您是否传递了带有协议的 url。错误“仅支持 HTTP(S) 协议”意味着既没有找到 HTTP 也没有找到 HTTPS 协议。