0

我在 TypeScript 中设置了一个非常简单的类,以使用 Axios 作为 HTTP 客户端从 Google 访问“放置自动完成”API,但请求失败并返回 CORS 错误。

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

无法加载 https://maps.googleapis.com/maps/api/place/queryautocomplete/json?key= &input=fre:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“ http://localhost:8080 ”。

如何做好?

4

1 回答 1

1

我自己偶然发现了这个问题。基本上,如果您从浏览器发出请求,则必须使用 Google Maps Javascript API。对于其他 Google 图书馆,例如 Google Place Library,您的请求必须来自服务器。这个 github 问题实际上很好地解释了这一点:https ://github.com/googlemaps/google-maps-services-js/issues/59#issuecomment-399626833

于 2018-10-02T19:41:44.037 回答