我正在尝试使用node、express和一个cors-anywhere实例为我的arcgis-js-api应用程序设置一个代理。我的服务器文件如下所示:
import express from 'express';
import cors from 'cors';
import corsAnywhere from 'cors-anywhere';
const { PORT } = process.env;
const port = PORT || 3030;
var app = express();
let proxy = corsAnywhere.createServer({
originWhitelist: [], // Allow all origins
requireHeaders: [], // Do not require any headers.
removeHeaders: [], // Do not remove any headers.
});
app.use(cors());
app.get('/proxy/:proxyUrl*', (req, res) => {
req.url = req.url.replace('/proxy/', '/');
proxy.emit('request', req, res);
});
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(port, () => {
console.log(`App listening on port ${port}`);
});当我转到http://localhost:3030/proxy/https://maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer?f=json时,我转到我的目标json没有问题,正确地附加了access-control-allow-origin: *。
在我的前端html (一个arcgis-js-api应用程序)中,我调用了相同的url:
var layer = new MapImageLayer({
url: 'http://localhost:3030/proxy/https://maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer?f=json',
});我的网络选项卡显示的响应不是预期的JSON,而是cors-anywhere代理的文本:

对于那些熟悉arcgis-js-api的用户,您还可以预先配置代理的使用:
urlUtils.addProxyRule({
urlPrefix: 'maps.disasters.nasa.gov',
proxyUrl: 'http://localhost:3030/proxy/',
});如果这样做,网络选项卡显示对localhost:3030/proxy/<url>的调用返回的是index.html页面,而不是所需的json。
为什么当我直接通过浏览器访问url时,代理会给出预期/必需的结果,而从前端文件调用时却不会?感谢您的阅读。
发布于 2020-12-09 21:30:08
我检查了浏览器控制台,注意到发送到代理的url而不是这个
http://localhost:3030/proxy/https://maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer?f=json
看起来像这样
http://localhost:3030/proxy/https:/maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer?f=json
不确定为什么会发生这种情况,但作为一种快速修复方法,您可以替换
req.url = req.url.replace('/proxy/', '/');使用
req.url = req.url.replace('/proxy/https:/', '/https://');

https://stackoverflow.com/questions/65176887
复制相似问题