设置代理来处理 arcgis js 的 CORS api

Set up proxy to handle CORS for arcgis js api

序幕:

我正在尝试将图层拉入我的 arcgis-js-api 应用程序,但我遇到了困难。图层在这里:

https://maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer

我正在尝试以这种方式添加它:

export const SC2Sept29 = new MapImageLayer({
    url:
        'https://maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer/547',
});

当 运行 我的应用程序出现经典 CORS 错误时

Access to fetch at 'https://maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer?f=json' from origin 'https://cdpn.io' has been blocked by CORS policy: 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.

这来自 this codepen, but the same happens when developing locally with vscode live server 或 webpack-dev-server。这不会发生在其他图层上,只是来自 maps.disasters.nasa.gov 服务器上的图层。

正在尝试设置代理

我从线程 CORS error when trying to access NASA layer that I need to set up a proxy for anything coming from this server. Their advice was to follow these instructions to set up a proxy, and to use one of arcgis's ready-made proxies. Personally, I am finding the instructions for the proxies repo to be lacking. All of my experience in setting up server-side apps is with nodejs, and I am not understanding the instructions for how to do this. The codepen I linked, for now, tries to use the CORS anywhere proxy 得到了一些建议,但在 esr/core/urlUtils:

中设置了它
urlUtils.addProxyRule({
  urlPrefix: 'maps.disasters.nasa.gov',
  proxyUrl: 'https://cors-anywhere.herokuapp.com',
});

但这给出了一个错误,指出 Unexpected token T in JSON at position 0。我可以在网络选项卡中看到浏览器确实在尝试访问正确的层 URL,正确地以 cors anywhere proxy URL 为前缀。但是响应本身只是 cors anywhere proxy 的文本,因此出现错误:

正如我提到的,我的开发环境是 vscode 实时服务器和一个 webpack 开发服务器,具体取决于我构建的应用程序的哪个部分。我的目标生产环境是 github 页——我真的没想到这个应用程序需要后端。如果我需要服务器端提供代理,我可以将其作为全栈应用程序托管在 heroku 甚至 AWS 上。尝试使用预先提供的 arcgis 代理时,我遇到了同样的问题。例如,我将他们的代理 repo 克隆到我的目录:

当配置 urlUtils 以引用这些代理之一时,它确实这样做了,但只是 returns 代理文件的文本内容并给我 Unexpected token T in JSON at position 0 错误。在 esri 论坛上有很多关于 IIS 的讨论,但我是一个 mac 的人,没有这方面的经验。 Esri 在 .NET、java 或 PHP、none 中提供代理,我对此有经验。

我怎样才能摆脱这些 cors 错误并正确地将层从 nasa 服务器拉到我的应用程序中。如果我需要一个代理,我该如何设置一个既适用于我的开发环境又适用于生产环境的代理?我很难找到适用于这种情况的适合我水平的教程。感谢阅读。

好的,我想现在我们可以总结一下了。

为了使其正常工作,您需要设置代理。正如您提到的,ESRI 提供了一些不同技术的实现。

我 fork 他们的存储库,以便使用 docker 和 docker-compose 包含一个简单的测试设置。 resource-proxy fork

克隆后 运行,

sudo docker-compose -f docker-compose.php.yml up -d --build

测试代理,

http://localhost:8082/proxy?ping

您还将在其中找到示例 nasa-service.html,其中显示了应用程序和代理的正确配置(全部在 PHP 文件夹中)。

只需运行http://localhost:8082/nasa-service.html.

这里的关键是应用程序需要与代理同源。