2
votes

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)
}

}

2
Which backend language and framework are you requesting, Java, Node.js etc?onuriltan
It's an external API, I dont know which language it is. It works in Postmanemibo34
That external api is blocking requests that are coming from clients, so you need to create a backend for frontend and made your request from that backend to pass corsonuriltan
Okey I want test it with Java Spring boot Thanks @onuriltanemibo34

2 Answers

10
votes

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.

3
votes

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?