Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable CORS in fetch api [duplicate]

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 => {
like image 684
johntanquinco Avatar asked Jun 25 '18 06:06

johntanquinco


People also ask

How do I allow CORS in fetch API?

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.

What happens if you enable CORS?

Enabling CORS That means that you can enable CORS on your server and access the resources you need from any origins you grant permission to. A server that's been configured to support CORS returns a few different headers to let the browser know whether cross-domain requests are allowed.

Is it safe to enable all CORS requests?

It is fairly secure, but there are ways to circumvent things. For example, an attacker could use a DNS poisoning technique to cause a preflight request to hit the actual server, but send the actual CORS request to the rogue server.


1 Answers

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.

like image 167
Kishan Mundha Avatar answered Oct 10 '22 18:10

Kishan Mundha