Victor Castro
Victor Castro

Reputation: 1242

CORS error when I try to use google place autocomplete API with Axios

I set up a very simple class in TypeScript to access the "Place autocomplete" API from Google using Axios as HTTP client but the request failed and returns a CORS error.

import axios from 'axios'

export default class GoogleRequester {
  private apiKey: string = ''

  constructor (apiKey: string) {
    this.apiKey = apiKey
  }

  placesAutocomplete (query: string) {
    let requestString = `https://maps.googleapis.com/maps/api/place/queryautocomplete/json?key=${this.apiKey}&input=${encodeURIComponent(query)}`
    return axios.get(requestString)
  }
}

Failed to load https://maps.googleapis.com/maps/api/place/queryautocomplete/json?key=&input=fre: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

How to do it well ?

Upvotes: 0

Views: 6930

Answers (1)

findniya
findniya

Reputation: 31

Just stumbled on this problem myself. Basically, you have to use Google Maps Javascript API if your making a request from the Browser. For other Google Libraries like the Google Place Library your request has to come from the server. This github issue actually explains this really well: https://github.com/googlemaps/google-maps-services-js/issues/59#issuecomment-399626833

Upvotes: 3

Related Questions