-2

So I'm not quite sure what I'm doing wrong, but I'm bumping into a cross-origin request blocked issue when trying to make an API call to chasing-coins. Two reasons shown:

  1. CORS header 'Access-Control-Allow-Origin' missing
  2. CORS request did not succeed

This is my code

fetch('https://chasing-coins.com/api/v1/coins', {
  method: 'GET',
  headers: { 'Access-Control-Allow-Origin': '*' }
})
.then(response => console.log(response))

What am I doing wrong?

Edit: Not sure if this makes a difference but I'm using localhost and tested both firefox and chrome, both don't work

jww
  • 97,681
  • 90
  • 411
  • 885
user3026715
  • 404
  • 3
  • 5
  • 19
  • Access-Control-Allow-Origin is a response header for servers to send back, not a request header to set in your frontend code. The problem is that `https://chasing-coins.com/api/v1/coins` isn’t sending the Access-Control-Allow-Origin response header. You can’t fix that by trying to send it from your frontend code instead. See the *How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems• section of the answer at https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141 – sideshowbarker Oct 07 '18 at 12:32

1 Answers1

1

This is related to a CORS issue with the server hosting the API. The source API has not set a configuration to allow browsers to request the resource from different origins, so any requests made from different origins with a browser will end up a pre-flight error.

The pre-flight error occurs during the TCP/IP handshake request and it's at this moment that the origin is confirmed and if the server is not configured to handle cross origin requests, the browser will not fulfil the request as expected.

To get around this, you will need to use a backend server such as nodejs to query the API and server it to your front-end code. This will work because nodejs does not have a CORS policy when requesting resource from external APIs.

This is also why CURL and apps like Postman will work with the API, because the also don't enforce the CORS policy on the request.

Daniel Ram
  • 352
  • 2
  • 6