I was thinking that the SOP blocked all requests to other domains conform their rules BEFORE sending it, but I did a simple example in my machine and It wasn't quite what I expected:
1- I have a local server listening to port 8000 that will print the POST data sent to /api
URL.
2- I have another local server that serves a page with the following script: fetch('http://localhost:8000/api', {method: 'post', body: 'Sending data.'});
. I changed the hostname to access this page with foo.com
in my browser.
When I access foo.com
, my cross domain request is executed and I can see the CORS error in Chrome Dev Tools: No 'Access-Control-Allow-Origin' header is present on the requested resource
, but in the server console the data was still received. I thought that the SOP existed to solve exactly this kind of problem. The way it works, It only guarantee that you can't get the response back. Is that so? Almost all web documents doesn't quite say that.
What am I missing? Or is my example wrong somehow?
Exactly as you say, that's a big misunderstanding by many people of what the same origin policy protects against and how CORS works.
The request is indeed made, the server processes it and creates the response. It's only the browser that stops the client from being able to access the results. This may easily give way to attacks like CSRF.
Preflight requests also have a role, but the point doesn't change, the same origin policy doesn't stop the request, it stops the response from reaching the caller in the browser.