Node.js调用Google Places API遇language_code无效错误求助
问题
我尝试编写脚本调用新版Google Places API,curl请求能正常运行:
curl -X POST -d '{ "textQuery" : "101 Gowrie, Amsterdam" }' \ -H 'Content-Type: application/json' -H 'X-Goog-Api-Key: ...' \ -H 'X-Goog-FieldMask: places.displayName,places.formattedAddress' \ 'https://places.googleapis.com/v1/places:searchText'
但Node.js的fetch请求却返回错误:
fetch("https://places.googleapis.com/v1/places:searchText", { method: "POST", body: JSON.stringify({ textQuery: "101 Gowrie, Amsterdam" }), headers: { "Content-Type": "application/json", "X-Goog-Api-Key": apiKey, "X-Goog-FieldMask": "places.displayName,places.formattedAddress" } }).then(res => res.json()).then(console.log).catch(console.log)
错误信息:
{ "error": { "code": 400, "message": "Invalid language_code: '*'. See full list of supported languages at https://developers.google.com/maps/faq#languagesupport.\n", "status": "INVALID_ARGUMENT" } }
我从未设置过*作为语言代码,想要获取英文结果,对此感到困惑。
解决方案
这个问题是因为Node.js环境中,fetch会默认传递带通配符*的Accept-Language请求头,新版Google Places API会将该值解析为language_code参数,触发验证失败。
可以通过两种方式解决:
- 显式指定请求体的
languageCode字段:在POST的JSON body中添加languageCode参数,设置为目标语言(比如英文用"en"),覆盖默认行为:
fetch("https://places.googleapis.com/v1/places:searchText", { method: "POST", body: JSON.stringify({ textQuery: "101 Gowrie, Amsterdam", languageCode: "en" }), headers: { "Content-Type": "application/json", "X-Goog-Api-Key": apiKey, "X-Goog-FieldMask": "places.displayName,places.formattedAddress" } }).then(res => res.json()).then(console.log).catch(console.log)
- 添加
Accept-Language请求头:在headers中设置明确的语言值,替换默认的通配符:
fetch("https://places.googleapis.com/v1/places:searchText", { method: "POST", body: JSON.stringify({ textQuery: "101 Gowrie, Amsterdam" }), headers: { "Content-Type": "application/json", "X-Goog-Api-Key": apiKey, "X-Goog-FieldMask": "places.displayName,places.formattedAddress", "Accept-Language": "en" } }).then(res => res.json()).then(console.log).catch(console.log)
两种方法都能让API正确识别目标语言,避免解析出无效的*值。
内容的提问来源于stack exchange,提问作者Simon H
相关产品推荐
相关产品推荐

