31

I am getting the following error message that unable me to continue

Failed to load https://site/data.json: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. localhost/:1 Uncaught (in promise) TypeError: Failed to fetch

I am trying to enable CORS in my react js file but I was not able to get the expected result. I have installed a chrome extension and it work. But to use this in production site, I need to enable it inside my code. How should I properly arrange the code to enable the CORS.

fetch(URL, {
  mode: 'cors',
  headers: {
    'Access-Control-Allow-Origin':'*'
  }
})
  .then(response => response.json())
  .then(data => {
Virb
  • 1,580
  • 1
  • 13
  • 23
johntanquinco
  • 733
  • 1
  • 5
  • 17

1 Answers1

28

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

Kishan Mundha
  • 2,488
  • 15
  • 24
  • 1
    What if I'm trying to scrape Google results? Like, I want to request `https://www.google.com` from my client code and parse the results. Is it possible? I'm getting the same error that he was getting. Does it mean that google.com does not allow CORS requests to its main search page? Thanks. – cbdeveloper Mar 12 '19 at 09:22
  • 6
    If you want to fetch any other server like google or facebook and that server doesn't provide access, you might need a server to handle this. In server you can fetch response from google and send back to client. – Kishan Mundha Mar 12 '19 at 09:25
  • I think is a typo, it's `no-cors` that returns an opaque response, see https://stackoverflow.com/a/43268098/6324591 – mcjlnrtwcz Feb 11 '21 at 16:17