【发布时间】: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” 访问。
如何做好?
【问题讨论】:
-
不要使用 Axios。关注the documentation。使用 Google 的 API 客户端库。
-
使用 corsanywhere 怎么样?常量 PROXY_URL = 'cors-anywhere.herokuapp.com'; axios.get(PROXY_URL + requestString)
标签: javascript typescript google-places-api googleplacesautocomplete