Reputation: 45
I am a little confused on the security provided by CORS. Below are two HTTP requests that are practically the same, one works the other does not, one is via curl the other is javascript in the browser.
Terminal
$ curl https://www.google.com/
--> Returns a page
Browser:
// Open the console in the browser (or spin put localhost)
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.google.com");
xhr.send();
--> CORS Error
Try again:
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.google.com");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
xhr.setRequestHeader("Access-Control-Allow-Headers", 'Origin,Authorization,Content-Type,X-Auth-Token');
xhr.setRequestHeader("Access-Control-Allow-Credentials", 'true')
xhr.send();
--> CORS Error still
So I am guessing the google.com server has it set to only accept requests from the google domain. But when I curl from my terminal that isn't part of the google domain I get a 200 response with HTML, ect.
So why would the server respond to my terminal with no domain, but doesn't respond when I use javascript in the browser?
Thanks ^.^
Upvotes: 0
Views: 2636
Reputation: 7
CORS is a feature provided by the browser. CORS is a mechanism which aims to allow requests made on behalf of you and at the same time block some requests made by rogue JS and is triggered whenever you are making an HTTP request to:
Please find the attached article - https://medium.com/@baphemot/understanding-cors-18ad6b478e2b
Upvotes: -1
Reputation: 157
CORS is a security feature that in the end is implemented by your browser. Which is why you would never see CORS errors when curling from a terminal. See also: this post from mozilla
which says:
Cross-Origin Resource Sharing (CORS (en-US)) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.
Upvotes: 3