【问题标题】:Here Maps Geocode API leads to Cross-Origin error这里 Maps Geocode API 导致 Cross-Origin 错误
【发布时间】:2020-09-17 00:23:58
【问题描述】:

我在这里使用第一个示例来获取基于地址的地理坐标: https://developer.here.com/documentation/maps/3.1.15.1/dev_guide/topics/geocoding.html

我的 JavaScript 编码看起来与官方文档中的几乎相同:

var platform = new H.service.Platform({
  'apikey': 'HERE IS MY API KEY'
});

// Get an instance of the geocoding service:
var service = platform.getSearchService();

service.geocode({
  q: 'Berlin'
}, (result) => {
  result.items.forEach((item) => {
    console.log("test");
  });
}, alert);

但是,当发送地理编码请求时,我收到以下错误:

Access to XMLHttpRequest at '**https://geocode.search.hereapi.com/v1/geocode?xnlp=CL_JSMv3.1.16.1&apikey=[HERE IS MY API KEY]&q=Berlin**' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

API 密钥发送正确,为什么我仍然收到 CORS 错误? 如果我在浏览器中手动输入请求 URL,我会得到响应,一切都很好。

【问题讨论】:

    标签: maps geocoding here-api geocode


    【解决方案1】:

    是的,服务器会帮助解决这个问题。我在这里建议替代方案。

    您可以使用 HERE Maps REST 进行地理编码,也可以查看文档 — https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-geocode-brief.html

    由于历史上并非所有浏览器都支持 CORS(了解有关 CORS 的更多信息 — https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS),因此有一种方法称为 JSONP。在旧文档https://developer.here.com/documentation/places/dev_guide/topics/request-cross-domain-js.html 中查看一些 JSONP 说明。

    最终https://www.npmjs.com/package/jsonp npm 包可能是一个很好的跟进,我们可以在安装包后得到类似的东西 (npm install jsonp --save)。

    import jsonp from 'jsonp';
    
    
    jsonp('https://geocode.search.hereapi.com/v1/geocode?q=5+Rue+Daunou%2C+75000+Paris%2C+France&apiKey=my-api-key', 
    null, 
    (err, data) => {
      if (err) {
        console.error(err.message);
      } else {
        console.log(data);
      }
    });
    
    

    根据我的经验,这很有效。

    【讨论】:

      【解决方案2】:

      如果您通过在浏览器中打开文件来测试此代码,您可能会收到此错误。我建议使用本地服务器进行测试。

      【讨论】:

        猜你喜欢
        • 2012-11-13
        • 1970-01-01
        • 2022-07-01
        • 1970-01-01
        • 2021-08-06
        • 2020-02-27
        • 1970-01-01
        • 2022-12-10
        • 1970-01-01
        相关资源
        最近更新 更多