【发布时间】:2020-06-26 23:35:08
【问题描述】:
我能够执行 Google Geolocation API 文档提供的以下cURL 操作。
example.json
{
"considerIp": "false",
"wifiAccessPoints": [
{
"macAddress": "00:25:9c:cf:1c:ac",
"signalStrength": -43,
"signalToNoiseRatio": 0
},
{
"macAddress": "00:25:9c:cf:1c:ad",
"signalStrength": -55,
"signalToNoiseRatio": 0
}
]
}
然后我在终端中运行以下命令并获取 GPS 坐标。
$ curl -d @your_filename.json -H "Content-Type: application/json" -i "https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY"
但是,当我尝试使用 fetch 将其作为 POST 请求执行时,出现以下错误。
{
error: {
code: 400,
message: 'Invalid JSON payload received. Unexpected token.\n[object Object]\n ^',
errors: [ [Object] ],
status: 'INVALID_ARGUMENT'
}
}
我尝试以不同的方式重写我的选项和请求正文,但没有找到解决方案。我已经看到this 的回答,但它并没有真正提供有关获取请求的信息。这个问题指的是手机信号塔,而我正在使用 wifiAccessPoints,但我认为请求的结构是相似的。下面是我的请求体,和example.json一样。
const body = {
"considerIp": "false",
"wifiAccessPoints": [
{
"macAddress": "00:25:9c:cf:1c:ac",
"signalStrength": -43,
"signalToNoiseRatio": 0
},
{
"macAddress": "00:25:9c:cf:1c:ad",
"signalStrength": -55,
"signalToNoiseRatio": 0
}
]
}
这是我的 POST 获取请求。
var url = "https://www.googleapis.com/geolocation/v1/geolocate?key=" + apiKey
fetch(url, {method: 'POST', headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
}, body: body})
.then(res=>res.json())
.then((json,err)=>{
if (err){
console.log(err)
} else {
console.log(json)
}
})
我的 API 密钥有效且不受限制(我也将它用于场所 API),当我在 cURL 操作中尝试我的密钥时,它返回了坐标响应。
是否甚至可以使用 fetch 向该 API 发出请求?我对其他选择持开放态度,我只是不能让它成为命令行请求。
【问题讨论】:
标签: google-maps geolocation google-geolocation