Search code examples
javascriptangularxmlhttprequestcors

No 'Access-Control-Allow-Origin' Angular 4 app


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.


Solution

  • 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.