jhamm
jhamm

Reputation: 25062

How do I make an http request with fetch in node? node-fetch

I am trying to make a request in node. Here is my code:

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

    return err;
  });

Here is the error that I get. TypeError: Only HTTP(S) protocols are supported

I have tried to create a new agent and pass it in the options like this:

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;
        }
    }
}

I still get the same error.

When I run this in the client, I can send an http or an https request to the same fetch and there isn't an issue. Apparently it is different on with node.

What is the best way to handle this?

Upvotes: 4

Views: 8233

Answers (1)

badly
badly

Reputation: 91

Check if you've passed a url with a protocol. Error "Only HTTP(S) protocols are supported" means that there's neither HTTP nor HTTPS protocol found.

Upvotes: 8

Related Questions