سؤال

I've seen this pattern pop up in a couple of different teams. They have a server with a REST API and a frontend web project.

What commonly happens is the frontend developer finds their requests are being blocked by CORS, and they create a REST API for the frontend that just passes requests through to the main backend. This API eventually catches some business logic and turns into its own server, handling half of the backend responsibility separate from the true backend server.

How can this pattern be prevented? It feels wrong to spread business logic across two API projects and to have to run two APIs to use the frontend. Is there a proper way to make a "set-and-forget" CORS proxy for the frontend, without creating a dumping ground?

هل كانت مفيدة؟

المحلول

The only scenario where I can see that configuration is when main API is not published with a public subdomain, so you may mask it publishing an intermediate public “backend” to proxy requests to the API in the private network OR you have a front end-backend (Let’s say a CMS with a different ad-hoc front end in AngularJS, React or any other Client-Side technology ) that consume services from other API, so you have a mix of CMS functionalities and data coming from the other API, I have seen both cases.

Most CORS problems come from misunderstanding of this mechanism. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

If API is publicly exposed, then you just need to configure the Access-Control-Allow-Origin: For the calling subdomain (origin of request) so you only have to worry that nothing is changing headers when they’re sent.

Of course CORS serves for the purpose of safely sharing data between different servers, hosting different applications, as API may reject any request not coming from the subdomain specified at Access-Control-Allow-Origin:

Otherwise having two backends with different or complementary business logic may result on a disaster, as any change done to the front end may easily result in changing code in the two backends which makes it harder to maintain.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى softwareengineering.stackexchange
scroll top