0

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 ?

Fateme Fazli
  • 11,582
  • 2
  • 31
  • 48
Victor Castro
  • 1,232
  • 21
  • 40
  • 2
    Don't use Axios. Follow [the documentation](https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API). Use Google's API client library. – Quentin May 01 '18 at 10:14
  • how about using corsanywhere? const PROXY_URL = 'https://cors-anywhere.herokuapp.com/'; axios.get(PROXY_URL + requestString) – happyZZR1400 May 01 '18 at 10:31
  • Possible duplicate of [XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' Google maps](https://stackoverflow.com/questions/43294257/xmlhttprequest-cannot-load-no-access-control-allow-origin-header-is-present-on) – xomena May 01 '18 at 21:26

1 Answers1

3

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

findniya
  • 31
  • 2
  • 1
    Please share an attempt at solving the problem as a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve), and include it as an [edit](https://stackoverflow.com/help/privileges/edit) to your question. –  Oct 02 '18 at 19:46