【发布时间】:2021-03-01 07:45:57
【问题描述】:
我查看了其他答案,但除非我没有得到答案,否则他们不会回答我的问题。
环境
NodeJS 12.19.0 VueJS 2.6.10 Axios 0.15.3
Axios 的当前配置:
axios.defaults.headers.common['Authorization'] = store.apiKey
axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded, application/json'
axios.defaults.headers.common.crossDomain = true
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = 'https://maps.googleapis.com/maps/api/*'
axios.defaults.headers.common['Accept'] = 'application/json, text/plain, text/html, application/xhtml+xml, application/xml, */*'
我也试过这个:
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*, https://maps.googleapis.com/'
我的 Axios 调用(来自 mixin 中的方法部分):
...
loadPoi (lat, lng, radius = null, type = null) {
if (!lat || !lng) {
this.$message({message: 'Unable to load Places of Interest: invalid lat or lng values',
type: 'warning'
})
return
}
let url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + lat + ',' + lng + (radius ? '&radius=' + radius : '') + (type ? '&type=' + type : '') + '&key=' + GOOGLE_API_KEY
console.log('loadPoi', url)
/*
var xmlHttp = new XMLHttpRequest()
xmlHttp.open('GET', url, false) // false for synchronous request
xmlHttp.send(null)
console.log(xmlHttp.responseText)
*/
axios.get(url).then(response => {
this.places = response.results
})
.catch(e => {
this.$message({message: 'Unable to load Places of Interest [' + e + ']',
type: 'error'
})
})
},
...
如您所见,即使尝试 raw JavaScript 调用,结果也一样。
相同的 URL 在浏览器中工作得很好。
但是当我从 Axios 访问它时,我得到了这个错误:
GET /maps/api/place/nearbysearch/json?location=2.0978,103.6063&radius=5000&key=[KEY] undefined
Host: maps.googleapis.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:82.0) Gecko/20100101 Firefox/82.0
Accept: application/json, text/plain, text/html, application/xhtml+xml, application/xml, */*
Accept-Language: en-GB,en;q=0.7,es-MX;q=0.3
Accept-Encoding: gzip, deflate, br
Authorization: undefined
crossDomain: true
X-Requested-With: XMLHttpRequest
Access-Control-Allow-Origin: https://maps.googleapis.com/maps/api/*
Origin: http://localhost:8080
DNT: 1
Connection: keep-alive
Referer: http://localhost:8080/
【问题讨论】:
-
不确定这是否是答案:stackoverflow.com/questions/48647369/… 如果是,为什么?
标签: vue.js google-maps axios cors