Reputation: 138
I have a web application where I want to use information from other web pages. A typical example would be to get weather information in XML format from a forecast service. Say "https://www.yr.no/place/United_States/New_York/New_York/varsel.xml". When I try to use a GET request with XMLHttpRequest I get the typical Cross-Origin error.
The simple solution to this is to make the server allow CORS. But what if I have no control over the given server? Is there any other way to request the data?
I have tried the Enable-CORS extension for Chrome, but this is not a good solution. Besides it doesn't work if the site your requesting data from needs authentication, like an username/password.
I can't seem to find any information about this problem, but if this is a duplicate I apologize.
Upvotes: 0
Views: 791
Reputation: 88086
For the simple case of just wanting to get the content of a publicly-available resource on the Web like https://www.yr.no/place/United_States/New_York/New_York/varsel.xml and do something with it in your frontend JavaScript code, you don’t need to set up your own proxy but can just use an existing open public CORS proxy like https://cors-anywhere.herokuapp.com/.
Instead of giving https://www.yr.no/place/United_States/New_York/New_York/varsel.xml
to the XHR/Fetch call (or jQuery.get()
or axios or whatever call), you give it this URL:
https://cors-anywhere.herokuapp.com/https://www.yr.no/place/United_States/New_York/New_York/varsel.xml
That sends the request through the open CORS proxy https://cors-anywhere.herokuapp.com which adds the Access-Control-Allow-Origin
response header to it and then passes that back to your requesting frontend code as the response.
That response with the Access-Control-Allow-Origin
response header is what the browser sees, so the browser allows your frontend JavaScript code to actually access the response.
But if the site you’re requesting data from needs authentication then you don’t want to make the request through a third-party proxy like https://cors-anywhere.herokuapp.com—because then you’d be exposing the credentials to a third party (the owner of the third-party proxy).
But for that case it’s fairly quick and easy to instead set up your own private proxy using the code from https://github.com/Rob--W/cors-anywhere or some such—or to otherwise set up some simple proxying mechanism in your existing backend code.
Upvotes: 2