问题
I am trying to set up a proxy using node, express, and an instance of cors-anywhere for my arcgis-js-api app. My server file looks like this:
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}`);
});
When I go to http://localhost:3030/proxy/https://maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer?f=json
, I get to my target json no problem, with access-control-allow-origin: *
correctly tacked on.
In my front end html (an arcgis-js-api app), I am calling that same 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',
});
My network tab shows a response not of the expected JSON, but of the text of the cors-anywhere proxy:
For those familiar with the arcgis-js-api, you can also preconfigure use of a proxy:
urlUtils.addProxyRule({
urlPrefix: 'maps.disasters.nasa.gov',
proxyUrl: 'http://localhost:3030/proxy/',
});
If I do it this way, the network tab shows that the call to the localhost:3030/proxy/<url>
is returning the index.html page, not the desired json.
Why is the proxy giving the expected/required result when I access the url directly through the browser, but not when being called from my front end file? Thanks for reading.
回答1:
I checked the browser console and noticed that the url being sent to the proxy instead of this
http://localhost:3030/proxy/https://maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer?f=json
looks like this
http://localhost:3030/proxy/https:/maps.disasters.nasa.gov/ags04/rest/services/ca_fires_202008/sentinel2/MapServer?f=json
Not sure why it's happening, but as a quick fix you can replace
req.url = req.url.replace('/proxy/', '/');
with
req.url = req.url.replace('/proxy/https:/', '/https://');
来源:https://stackoverflow.com/questions/65176887/cors-anywhere-returning-proxy-text-not-desired-target-resource