-4

I am fetching data from API but it didn't work. It's giving me the error like " Access to fetch at 'http://muslimsalat.com/lahore/false/5.json?key=API_KEY' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. "

When i fetch data in react-native mobile then it worked but when i fetch data in react desktop then it is not working.

Can anyone tell me what is the reason for this error and how can i solve it?

Zain Shabir
  • 120
  • 4
  • 15
  • 1
    You can enable CORS on muslimsalat.com if you own that server. Otherwise, there is nothing you can do unfortunately. If you are using a express, then check out https://github.com/expressjs/cors. – lomse Feb 20 '19 at 09:56
  • it is the error not for one api link, all api link is not working in react desktop, but it is working in react-native mobile application – Zain Shabir Feb 20 '19 at 09:58
  • @ZainShabir that's because the CORS protection is something you'll only have on the Web environment. It's a browser protection. – keul Feb 20 '19 at 09:59
  • 1
    Possible duplicate of [Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present) – keul Feb 20 '19 at 10:00
  • i don't know how to solve it, i am using react-redux desktop, but the link you give me, it's not in react brother – Zain Shabir Feb 20 '19 at 10:01
  • @ZainShabir let's start from the begginning - *do you own `muslimsalat.com`*? – Nino Filiu Feb 20 '19 at 10:14
  • @NinoFiliu No, I am just using their api link, – Zain Shabir Feb 20 '19 at 11:17
  • Ok. Then they have changed their CORS headers and **there is nothing you can change on your React app to bypass that**. – Nino Filiu Feb 20 '19 at 15:04

2 Answers2

0

Add CORS into API URL. You have to just add your local IP to your backend service(API). If you need proper code to let us know in which language you are using for backend API.

Akhil Thakur
  • 133
  • 8
0

CORS is a mechanism in which a domain can specify which other domains can make request to it. By default, there is no Access-Control-Allow-Origin header, which means that for example a script at stackoverflow.com cannot call google.com:

fetch('https://www.google.com')
  .then(console.log)
  .catch(console.error)
// Error: Failed to fetch

That is why a React app, that runs as a script, cannot fetch most content on the web.

However, a React Native app runs as an application, and not as a script, so it is not affected by CORS.

Nino Filiu
  • 12,893
  • 9
  • 48
  • 65