0

I am trying to fetch data using Axios, (URL: http://3.134.99.170:4000/upcomingMovies)

I am always getting this error: (Access to XMLHttpRequest at 'http://3.134.99.170:4000/upcomingMovies' from origin 'http://localhost:9000' 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.)

I have tried using fetch and superagent also, but the same error again.

Also, this is my code:

axios({
      method: "GET",
      url: "http://3.134.99.170:4000/upcomingMovies",
      headers: {
        'Access-Control-Allow-Headers': 'Content-Type, Accept, Access-Control-Allow-Origin, Access-Control-Allow-Methods',
        'Access-Control-Allow-Origin' : '*',
        'Access-Control-Allow-Methods' : 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
        "Content-type": "application/json"
      }
    })
    .then((response) => {
      setUpcomingMovies(response)
    })
    .catch((error) => {
      console.log(error)
    })
  • 1
    You have to whitelist your front-end ip/domain in your backend. you could read more about CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – senthil balaji Sep 29 '20 at 04:05
  • This API was provided by an institute, and I am sure they might be using it for many years now. This should not be the first problem for them? –  Sep 29 '20 at 04:07
  • 1
    I'm not sure about that. But definitely, this is something backend has to allow. any and every request you make will go through a `pre-flight options` request which will check for `cross-origin` headers and then only it will make the actual GET request. Your request is getting rejected at `OPTIONS` request and throws an error saying `your domain is blocked`. – senthil balaji Sep 29 '20 at 04:15

1 Answers1

0

if you need only run and test your code, you can use no-cors mode in browser ( as described here Disable same origin policy in Chrome) or use some extension for browser, which switchs off cors-restricted mode (like this https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf) to avoid the issue. But if you need avoid the issue in production, you need backend support, as senthil balaji mentioned before

elkabelaya
  • 16
  • 1
  • adding to elkabelaya, you could run chrome instance with `security rules disabled` in case of local development rather than disabling in your actual browser. to run chrome instance (security disabled version) refer for different OS https://stackoverflow.com/questions/35432749/disable-web-security-in-chrome-48 – senthil balaji Sep 29 '20 at 09:04