9

i get this fail on chrome:

Access to fetch at 'http://******/places?holiday_type=resort&currency=EUR&checkin=2019-11-01&checkout=2019-11-10&groups[]=1' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

My Code is:

getPlaces = async () => {
try {
  let response = await fetch(`${BASE_URL}/places?holiday_type=resort&currency=EUR&checkin=2019-11-01&checkout=2019-11-10&groups[]=1`,
    {
      method: 'GET',
      headers: new Headers({
        'Accept': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
        'Access-Control-Request-Method': 'GET, POST, DELETE, PUT, OPTIONS',
        'Authorization': 'Basic ' + Base64.encode(apiuser + ':' + apipassword) ,
      }),
    })

    console.log(response)
} catch (error) {
  console.log(error)
}

}

VLAZ
  • 26,331
  • 9
  • 49
  • 67
emibo34
  • 113
  • 1
  • 1
  • 3

2 Answers2

15

External APIs often block requests like this. I would guess that you are using something like an API-Key for your request which includes payment based on your calls. The problem is that every user can read your key when you call the API in your frontend. Thats why the server is block these.

You need to make a server on your own (e.g. with node.js), call your backend API and then "forward" your request the public API with your secret API key. Server-to-Server requests won't be blocked and your users can't exploit your API key. You should also make sure to that your backend server doesn't accepts request which is not your frontend if you want to make it public.

MichelleFuchs
  • 355
  • 3
  • 9
5

CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross-domain.

You can temporarily solve this issue by a chrome plugin called CORS.

copied from: How to allow CORS in react.js?

Reference: How to overcome the CORS issue in ReactJS?

Pardeep
  • 2,153
  • 1
  • 17
  • 37