Reputation: 87
I am trying to access this address: http://52.208.91.209:3000/?paging=1
Accessing manually works fine. Accessing via an Angular 4 request returns:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
I have googled it for a few hours and did not find a solution.
The only "solution" I have found is using Allow-Control-Allow-Origin plugin.
The address I am trying to access is not mine.
I am just trying to work with it.
I have even read about proxies when using ng serve with angular CLI but didnt fully understand.
All of the solutions I saw are simply a response headers problem on the server side. However, This is NOT my server so I cannot configure it.
Any help would be appreciated. Thank you.
Upvotes: 1
Views: 4290
Reputation: 1299
The solution I've found was to build my project with the right host using
ng build --production -host=myDomain.com
Upvotes: 0
Reputation: 88026
You can change your frontend JavaScript code to instead make the request through a public proxy.
To try that, change your code to use the following URL:
https://cors-anywhere.herokuapp.com/http://52.208.91.209:3000/?paging=1
That’ll cause the request to go to https://cors-anywhere.herokuapp.com
, a open CORS proxy that sends the request on to the http://52.208.91.209:3000/?paging=1
URL you want.
That proxy gets the response, takes it and adds the Access-Control-Allow-Origin
response header to it, and then finally passes that back to your requesting frontend code as the response.
So in the end because the browser sees a response with the Access-Control-Allow-Origin
response header, the browser allows your frontend JavaScript code to access the response.
Or use the code from https://github.com/Rob--W/cors-anywhere/ or such to set up your own proxy.
You need a proxy in this case because http://52.208.91.209:3000/?paging=1
itself doesn’t send the Access-Control-Allow-Origin
response header—and in that case your browser will not allow your frontend JavaScript code to access a response from that server cross-origin.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.
Upvotes: 4
Reputation: 795
You can't access that API the way you want to from the browser. There are security measures in place to prevent this from happening. If you do not control the source of the data, you cannot do anything to fix this. Your only option is to have your own server request the data, and you then go through your server to get the data.
Edit: You actually can do this if you only plan to run it locally. Chrome has flags to ignore this security measure. If you don't plan on using this on any machine other than your own, you can force chrome to allow this locally.
Upvotes: 0