【问题标题】:CORS error when I try to use google place autocomplete API with Axios当我尝试将 google place 自动完成 API 与 Axios 一起使用时出现 CORS 错误
【发布时间】:2018-10-11 09:07:48
【问题描述】:

我在 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” 访问。

如何做好?

【问题讨论】:

标签: javascript typescript google-places-api googleplacesautocomplete


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2019-01-20
  • 1970-01-01
  • 2015-07-28
  • 2017-02-02
  • 2021-03-01
  • 2011-05-15
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多