Ad

Can A REST API Works As A PROXY For CORS Issues?

- 1 answer

My problem is as follows :

I'm developping a web application with Angular. Angular application runs on the client's browser. In its logic, my application needs data from other-domain.com. I can't use directly XMLHttpRequest() because of CORS policy problems. (The web server other-domain.com producing data is not my domain and cannot add 'Control-Access-Allow-Origins')

So instead of having :

Angular ===>> other-domain.com (forbidden because of CORS)

I'm creating a REST API that will get data from other-domain.com and wraps this data with header 'Access-Control-Allow-Origin' : '*' before sending to client's Angular.

So my workflow becomes :

Angular ==>> my API server ==>> other-domain.com (allowed because request for other-domain does not execute on the browser)

Do you think my idea works well forevery request (GET, POST, adding cookies header) ? In that case the API I'm developping acts as a proxy, right ?

Thank you

Ad

Answer

Short answer: yes. In fact, there's packages and sites out there that will do this for you.

But I think another question is why you have the need to circumvent CORS restrictions. After all, it is working as intended and there's a reason for its existence in the first place.

If you have a backend already, can you add an endpoint where your backend will make the call to the other domain, and leave the browser to communicate only within your domain?

If you're only doing RESTful GETs and an opaque request (no credentials, no cookies, etc.) will suit your needs, you could also just use the fetch api with {mode: 'no-cors'}; however, you'd need to 'circumvent' the HttpClient to do so and you'd need a polyfill if you need to support IE.

Ad
source: stackoverflow.com
Ad