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

使用Fetch API调用OpenTopodata接口遇CORS及请求体未发送问题求助

解决opentopodata.org API调用问题

我尝试从api.opentopodata.org获取海拔数据时遇到了一系列问题:

初始POST请求代码

let dataSEND = {
    "locations":
    [
      {
       "latitude": lat,
       "longitude": lon
      }
    ]
};

const elev_response = await fetch('https://api.opentopodata.org/v1/gebco2020',{ 
 method: 'POST',
 headers:{
    'content-type': 'application/json'
  },
  body: JSON.stringify(dataSEND),
});

触发的CORS错误

Access to fetch at 'https://api.opentopodata.org/v1/gebco2020' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

添加mode: 'no-cors'后的错误

Failed to load resource: the server responded with a status of 400 ()
"error": "No locations provided. Add locations in a query string: ?locations=lat1,lon1|lat2,lon2.",
"status": "INVALID_REQUEST"
}

已知该API支持GET请求携带查询参数,示例请求返回正常:

{
"results": [
{
"dataset": "gebco2020",
"elevation": 515,
"location": {
"lat": 10,
"lng": 10
}
}
],
"status": "OK"
}

解决方案

  • 改用GET请求:
    该API设计为通过URL查询参数接收locations,而非POST请求体。直接构造包含经纬度的查询字符串即可:

    const lat = 10; // 替换为实际纬度值
    const lon = 10; // 替换为实际经度值
    const url = `https://api.opentopodata.org/v1/gebco2020?locations=${lat},${lon}`;
    
    const elev_response = await fetch(url);
    const result = await elev_response.json();
    console.log(result.results[0].elevation);
    
  • 处理跨域问题:
    如果GET请求仍遭遇CORS限制:

    • 后端代理:在自有服务器编写转发接口,前端调用该接口避免跨域
    • 开发环境临时方案:使用CORS浏览器插件(仅用于测试,生产环境禁用)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:55:33