Google Maps API fetch() 返回空,但使用浏览器上的 URL 返回 JSON



我正在研究一种从下面的 JSON 中获取"photo_reference"的方法;

{
"html_attributions" : [],
"results" : [
{
"formatted_address" : "Bandar Seri Begawan, Brunei",
"geometry" : {
"location" : {
"lat" : 4.903052199999999,
"lng" : 114.939821
},
"viewport" : {
"northeast" : {
"lat" : 4.9665412,
"lng" : 115.0004731
},
"southwest" : {
"lat" : 4.845741299999999,
"lng" : 114.8757076
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "b4a5514750d9d7b0164125a220f5c111ae391f4d",
"name" : "Bandar Seri Begawan",
"photos" : [
{
"height" : 1200,
"html_attributions" : [
"u003ca href="https://maps.google.com/maps/contrib/102574123639894598769"u003eSharaf Vallappuzhau003c/au003e"
],
"photo_reference" : "CmRaAAAAKwcyWRgvz9w4IVkWulF7RtNl2bThJaCyfWbOI4hf8oQe-FKwLnpTh5VBbz2ZPo-fBusRkySxNZ2Pf2bfKoL_CljuTg4XnCwLfPxZU24ug-MEdilWgA4umy0nQvnmVs0gEhAFrFECNYCJUhZWvsUgEhRQGhSEcO6jK-mFFKpWXQ24TH15pKoZqQ",
"width" : 1600
}
],
"place_id" : "ChIJH3MLVLD1IjIRS-i6fMT4rO4",
"reference" : "ChIJH3MLVLD1IjIRS-i6fMT4rO4",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}

我通过在浏览器上打开此链接获得的。

但是我在下面的JS代码;

const targetUrl = `https://maps.googleapis.com/maps/api/place/textsearch/json?query=bandar+seri+begawan&key=API-KEY`;
fetch(targetUrl, {mode: 'no-cors'})
.then(response => response.json())
.then(function(response) {
console.log(response.results.photos.photo_reference)
})
.catch(e => {
console.log(e);
})
}

并在浏览器控制台中出现"语法错误:"JSON.parse:JSON 数据第 1 行第 1 列处数据意外结束"错误。

所以我决定通过使用下面的代码删除 json(( 来获得原始结果;

fetch(targetUrl, {mode: 'no-cors'})
.then(response => response)
.then(function(response) {
console.log(response)
})
.catch(e => {
console.log(e);
})

而是从浏览器控制台收到此错误;

Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, body: null, bodyUsed: false }

似乎 fetch(( 返回为空。但这不是当 URL 被键入浏览器时。

我需要激活或停用某种谷歌安全功能吗?对此的任何想法将不胜感激。

我猜 API 只考虑服务器使用,不允许客户端使用。您可能希望改用 JavaScript API。

<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
<小时 />
var service = new google.maps.places.PlacesService(document.getElementById('map'));

另请参阅:

如何使用 CORS 实现 JavaScript Google Places API 请求

如何通过 npm 安装谷歌地图?

https://developers.google.com/maps/documentation/javascript/overview#js_api_loader_package

最新更新