Google Apps Script调用地址验证API



代码简单明了。它的工作与邮差,但失败与Apps脚本。

function validateAddress () {
const url = 'https://addressvalidation.googleapis.com/v1:validateAddress?key=';
const apikey = '...';
let payload, options, temp;
payload = JSON.stringify({
"address": {
"addressLines": "1600 Amphitheatre Pkwy"
}
});
options = {
'muteHttpExceptions': true,
'method': 'POST',
'Content-Type': 'application/json',
'body': payload
}
temp = UrlFetchApp.fetch(url + apikey, options);
Logger.log(temp)
}

错误:

{
"error": {
"code": 400,
"message": "Address is missing from request.",
"status": "INVALID_ARGUMENT"
}
}

编辑:

options更改为

options = {
'muteHttpExceptions': true,
'method': 'POST',
'Content-Type': 'application/json',
'payload': payload
}

给了错误:

{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name "{"address":{"addressLines":"1600 Amphitheatre Pkwy"}}": Cannot bind query parameter. Field '{"address":{"addressLines":"1600 Amphitheatre Pkwy"}}' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name "{"address":{"addressLines":"1600 Amphitheatre Pkwy"}}": Cannot bind query parameter. Field '{"address":{"addressLines":"1600 Amphitheatre Pkwy"}}' could not be found in request message."
}
]
}
]
}
}

文档:https://developers.google.com/maps/documentation/address-validation/requests-validate-address

从文档中可以看出,addressLines是一个字符串数组,而不是字符串。这会改变什么吗?(我没有钥匙,所以我不能自己试试)。

更重要的是,你的options对象是不正确的(检查文档)。应该是

options = {
'muteHttpExceptions': true,
'method': 'POST',
'contentType': 'application/json',
'payload': payload
}

我不知道为什么它的工作,但改变options

options = {
'muteHttpExceptions': true,
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
},
'payload': payload
}

解决问题

最新更新