单位内部有个 ArcGIS 的服务器,现在需要加载上面的地理要素图层,已经确认 ArcGIS 服务器是允许跨域的,之前使用 Jq 或原生 JS 写没有跨域问题,vue 使用 ArcGIS API for JS 4.19
直接访问提示跨域问题,代码和报错如下
let AHDX_ZH0717 = new TileLayer({
title: "AHDX_ZH0717",
url: "http://10.34.x.x:6080/arcgis/rest/services/AHDX_ZH0717/MapServer",
});
map.add(AHDX_ZH0717);
// 提示跨域信息
Access to image at 'http://10.34.x.x:6080/arcgis/rest/services/AHDX_ZH0717/MapServer/tile/7/52/105?blankTile=false' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
然后想到了使用 nginx 反向代理,nginx 配置文件如下
location /gisserver {
add_header Access-Control-Allow-Origin '*';
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
proxy_pass http://10.34.x.x:6080/arcgis/;
proxy_read_timeout 600s;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
# ArcGIS Server 要求必须添加 X-Forwarded-Host 反代标头
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
此时 vue 项目的代码改为(nginx 在本地 9090 端口)
let AHDX_ZH0717 = new TileLayer({
title: "AHDX_ZH0717",
url: "http://127.0.0.1:9090/gisserver/rest/services/AHDX_ZH0717/MapServer",
});
map.add(AHDX_ZH0717);
// 提示跨域配置重复
Access to fetch at 'http://127.0.0.1:9090/gisserver/rest/services/AHDX_ZH0717/MapServer?f=json' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://127.0.0.1:8080, *', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
// 如果注释掉 nginx 配置文件的跨域设置则提示
Access to image at 'http://127.0.0.1:9090/gisserver/rest/services/AHDX_ZH0717/MapServer/tile/7/52/106?blankTile=false' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
现在头都大了,有没有好兄弟知道咋解决
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.