๐ช๐ต๐ฎ๐ ๐ถ๐ ๐๐ฟ๐ผ๐๐-๐ข๐ฟ๐ถ๐ด๐ถ๐ป ๐ฅ๐ฒ๐๐ผ๐๐ฟ๐ฐ๐ฒ ๐ฆ๐ต๐ฎ๐ฟ๐ถ๐ป๐ด (๐๐ข๐ฅ๐ฆ)?
Browsers use CORS, a method, to prevent websites from requesting data from different URLs. A request from a browser includes an origin header in the request message. The browser allows it if it gets to the server of the exact origin; if not, the browser blocks it.
We can deal with CORS issues on the backend. Cross-origin requests require that the values for origin and ๐๐ฐ๐ฐ๐ฒ๐๐-๐๐ผ๐ป๐๐ฟ๐ผ๐น-๐๐น๐น๐ผ๐-๐ข๐ฟ๐ถ๐ด๐ถ๐ป in the response headers match and it is set by the server. When you add an origin to the backend code, the CORS middleware only permits this URL to communicate with other origins and utilize it for cross-origin resource requests.
There are two ways to fix CORS issues:
๐ญ. ๐๐ผ๐ป๐ณ๐ถ๐ด๐๐ฟ๐ฒ ๐๐ต๐ฒ ๐๐ฎ๐ฐ๐ธ๐ฒ๐ป๐ฑ ๐๐ผ ๐๐น๐น๐ผ๐ ๐๐ข๐ฅ๐ฆ
Server can let all domains with ย ๐๐ฐ๐ฐ๐ฒ๐๐-๐๐ผ๐ป๐๐ฟ๐ผ๐น-๐๐น๐น๐ผ๐-๐ข๐ฟ๐ถ๐ด๐ถ๐ป: *. This actually turns off same-origin policy, which is not recommended. Another optin would be only to allow particular domain, which is better option, e.g., ๐๐ฐ๐ฐ๐ฒ๐๐-๐๐ผ๐ป๐๐ฟ๐ผ๐น-๐๐น๐น๐ผ๐-๐ข๐ฟ๐ถ๐ด๐ถ๐ป: ๐ต๐๐๐ฝ๐://๐๐ผ๐บ๐ฒ๐ฑ๐ผ๐บ๐ฎ๐ถ๐ป.๐ฐ๐ผ๐บ.
๐ฎ. ๐จ๐๐ฒ ๐ฎ ๐ฃ๐ฟ๐ผ๐
๐ ๐ฆ๐ฒ๐ฟ๐๐ฒ๐ฟ
We can use a proxy server to call external API. It acts as a middleware between client and the server. If the server doesn't return proper headers defined by CORS, we can add them in the proxy.
Image credits: RapidAPI
#softwareengineeringย
#programmingย
#apiย
#apidesign #techworldwithmilan