Javascript 尝试将google place autocomplete API与Axios一起使用时出现CORS错误
我在TypeScript中设置了一个非常简单的类,使用Axios作为HTTP客户端从Google访问“Place autocomplete”API,但请求失败并返回CORS错误Javascript 尝试将google place autocomplete API与Axios一起使用时出现CORS错误,javascript,typescript,google-places-api,googleplacesautocomplete,Javascript,Typescript,Google Places Api,Googleplacesautocomplete,我在TypeScript中设置了一个非常简单的类,使用Axios作为HTTP客户端从Google访问“Place autocomplete”API,但请求失败并返回CORS错误 import axios from 'axios' export default class GoogleRequester { private apiKey: string = '' constructor (apiKey: string) { this.apiKey = apiKey }
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)
}
}
加载失败
&输入=fre:
请求的服务器上不存在“Access Control Allow Origin”标头
资源。因此,不允许使用源“”
进入
如何做好这件事?我自己刚刚偶然发现了这个问题。基本上,如果您从浏览器发出请求,您必须使用Google Maps Javascript API。对于其他Google库,如Google Place库,您的请求必须来自服务器。
github的这个问题实际上很好地解释了这一点:不要使用Axios。跟着。使用谷歌的API客户端库。使用corsanywhere怎么样?const PROXY_URL='';获取(PROXY_URL+requestString)的可能重复项请将解决问题的尝试作为一个共享,并将其作为一个添加到您的问题中。