BobbyOrr4
BobbyOrr4

Reputation: 402

Why is my Axios fetch giving CORS errors?

I have spent more than 3 hours trying to research and find a solution to this. I have looked at numerous other answers on StackOverflow, and nothing was able to help. List of my research at the bottom

I am trying to access a public API.

When I do curl it is fully accessible.

When I try to access it in a React app, I get an error.

Here is my code:

const API = 'https://btcilpool.com/api/status';
const config = {
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
        },
    };
axios.get(API, config);

Here is the error:

GET https://btcilpool.com/api/status net::ERR_HTTP2_PROTOCOL_ERROR
Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:84)
Uncaught (in promise) TypeError: Failed to fetch

Network Tab

Network Tab 2

Here is what the API looks like:

// 20210407103327
// https://btcilpool.com/api/status

{
  "x17": {
    "name": "x17",
    "port": 3737,
    "coins": 1,
    "fees": 3,
    "hashrate": 0,
    "workers": 282,
    "estimate_current": "0.00000000",
    "estimate_last24h": "0.00000000",
    "actual_last24h": "0.00000",
    "mbtc_mh_factor": 1,
    "hashrate_last24h": 7143330385.0569
  }
}

My Reasearch:

https://blog.container-solutions.com/a-guide-to-solving-those-mystifying-cors-issues

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

CORS error - my headers

Upvotes: 0

Views: 2362

Answers (1)

Arcturus
Arcturus

Reputation: 27065

CORS requirements are set by the host, there is nothing you can do about it except asking if they will allow CORS headers.

A workaround is using a proxy. So you'll make a request on your own server and pass the result back to your client.

Here is an example with a free proxy, though I do not recommend doing this in production:

// This will result in your error
axios
 .get('https://btcilpool.com/api/status')
 .then((response) => console.log('Response', response))
 .catch((error) => console.log('Error', error))
 

// This will give you your expected result
axios
 .get(`https://api.allorigins.win/get?url=${encodeURIComponent('https://btcilpool.com/api/status')}`)
 .then((response) => console.log('Response', response))
 .catch((error) => console.log('Error', error))

https://jsfiddle.net/51qhnfw0/

Upvotes: 1

Related Questions