I\'m writing a small script to access an external API for work. I originally did this in Python and everything worked fine.
I was then asked to try and do it in Javascr
From Mozilla's documentation:
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and Fetch follow the same-origin policy. So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.
Since Javascript in the browser uses XMLHttpRequest
and fetch
to make HTTP requests, they're subject to CORS policy enforcement.
More information on the reasons for CORS:
CORS is intended to allow resource hosts (any service that makes its data available via HTTP) to restrict which websites may access that data.
Example: You are hosting a website that shows traffic data and you are using AJAX requests on your website. If SOP and CORS were not there, any other website could show your traffic data by simply AJAXing to your endpoints; anyone could easily "steal" your data and thus your users and your money.
The external API you're using likely implemented a CORS policy intentionally. For example, if the API requires an application-level secret key for authentication, a CORS policy would discourage the use of that key in a public environment (namely the browser). Alternatively, the API may have a list of acceptable domain names for CORS that doesn't include the domain you're currently using.
Those are just a few examples; there could be any number of reasons for an API to implement CORS headers.