You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fetch调用Nominatim API获取JSON数据失败求助

解决Nominatim API在Node.js fetch中无法调用的问题

问题原因

Nominatim API有严格的请求规范,要求请求必须携带合法的User-Agent头,用于识别请求来源,避免恶意爬取或滥用。Node.js环境下的fetch默认使用的User-Agent会被Nominatim的服务器拦截,导致请求失败;而jsonplaceholder这类开放测试API没有这类限制,所以可以正常调用。

解决方案

在fetch请求中添加自定义的User-Agent头,示例代码如下:

fetch('https://nominatim.openstreetmap.org/search?q=Germany&format=json&limit=1', {
  headers: {
    'User-Agent': '你的项目名称/1.0 (你的联系邮箱,可选)'
  }
})
.then(response => {
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return response.json();
})
.then(json => console.log(json))
.catch(error => console.error('请求失败:', error));

注意事项

  • User-Agent需要真实反映你的项目信息,不要使用模糊或伪造的标识,这是Nominatim API的使用要求,违反可能会被封禁IP。
  • 新增错误处理逻辑可以帮你快速排查请求失败的具体原因,比如HTTP状态码异常等情况。

内容的提问来源于stack exchange,提问作者user20993186

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 13:40:34