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

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.

如何做好?

请您参考如下方法:

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!