0

I am working on react-app that uses google places API, my task is to get places in a selected location (location.lat, location.lng).

I created the next hook with the request URL:

useEffect(() => {
  if (location.lat && location.lng) {
    setUrl("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + location.lat + "," + location.lng + "&radius=2000" + <My_key> );  
    console.log("url = "+url);
    fetch(url, { 
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*"
      }
     })
    .then(response => response.json())
    .then(result => setPlacesList(result)); 
    console.log("places"+placesList);
  }
}, [location.lat, location.lng, url, placesList]);

But I faced with the next error:

Access to fetch at 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=26.8466937,80.94616599999999&radius=2000&key=XXXX' 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.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
Helen
  • 157
  • 1
  • 8
  • Is the value of `url` as printed with line : `console.log("url = "+url);` correct? State setter functions like `setUrl` are asynchronous. – Ajeet Shah Mar 28 '21 at 17:53
  • See [this related question](https://stackoverflow.com/q/42180788/2873538). – Ajeet Shah Mar 28 '21 at 17:56
  • This looks like it should be a GET request, not POST. – Ryan Mar 28 '21 at 18:02
  • Also, the `Access-Control-Allow-Origin` is a response header (expected from the server), and shouldn't be in your request. – Ryan Mar 28 '21 at 18:11
  • console.log("url = "+url); is Ok, and this one just printed the right url, and I can check that this url works (I can see the list of places), but my request still doesn't work. I tried to delete Access-Control-Allow-Origin and change POST to GET, but nothing changed. – Helen Mar 28 '21 at 19:18
  • It seems, that I managed to fix it by adding Allow CORS: Access-Control-Allow-Origin extension to my browser – Helen Mar 28 '21 at 23:22
  • Literally the [same question](https://stackoverflow.com/questions/66833076/google-places-api-gives-a-cors-error-in-the-react-project) was asked 24 hours before you asked yours and it has been asked too many times. You should **search** before asking. – MrUpsidown Mar 29 '21 at 07:07
  • 2
    Duplicate of [How to use CORS to implement JavaScript Google Places API request](https://stackoverflow.com/questions/42180788/how-to-use-cors-to-implement-javascript-google-places-api-request) – MrUpsidown Mar 29 '21 at 07:07

0 Answers0