google-maps-api-3reactjscorsgoogle-places-apiisomorphic-fetch-api

Sending a details request to Google Places API - (CORS error)


I'm trying to augment the collection of photos I have for public artworks in this project I'm working on with photos from the Google Places API. It says here that you can send a details request to get an array of ten photos. Eventually I will unpack the response to get Google's photo reference for each photo and make requests for each photo in the array and display it.

Unfortunately, this plan breaks when I send my details request. This is the exact error I'm getting:

Fetch API cannot load https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJ5zf5lfXKRIYR8rPafbwaL68&key=MY_API_KEY. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:4040' is therefore not allowed access. 
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I'm running this from my localhost and I'm pretty sure that matters. All of my other API calls (Google Maps API and a couple others) are written exactly as this is, so I'm a little confused why I'm getting the error. Here is the relevant code:

The actual API call:

export function getPhotos(placeID) {
  let obj = {
    method: 'GET'
  };
  return fetch('https://maps.googleapis.com/maps/api/place/details/json?placeid=' + placeID + '&key=MY_API_KEY')
    .then((response) => {
      if (response.status >= 400){
        throw new Error("Error getting photos for placeID: " + placeID)
      }
      return response.json()
    })
}

Let me know if you need any other information, I'd be happy to provide it. Thanks!


Solution

  • You need to use a server side proxy to prevent this error. It works when you access the url directly because you have no origin when you do that.

    Check this related SO question:

    You can either modify your API server so that CORS is enabled, or follow the instructions on the webpack-dev-server page under "Combining with an existing server" to combine asset serving with webpack-dev-server and your own API server.

    Hope this helps!