CORS error with Javascript but not with Python/PHP

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 Javascript. Now, I'm no programmer really, but I do know (or believe) that Javascript is largely for client-side, whereas PHP or Python are really for server-side operations. When I wrote the script in Python I had no problems, but in Javascript I get a

Response to preflight request doesn't pass access control check: No 
'Access-Control-Allow-Origin' header is present on the requested
resource.

error. From what I've read about CORS here and similar questions on Stack, that makes sense, but I don't really understand why I don't get a similar error in Python or PHP...

I'm fairly new to this so I'm probably missing a number of things, but I'd really appreciate any insight anyone can give me. If I've left out any important info, please let me know.

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.