HN2new | past | comments | ask | show | jobs | submitlogin

Browsers implement what they call the "same-origin policy" as a cross-site scripting prevention measure. This prevents you from using XMLHttpRequest calls on other hostnames/ports, which effectively means if you're making a static website on a host with no API endpoints, your website can't interact with any backend services. As a result, you can't save or load data from a server-side database or do a lot of other operations that traditional web applications can do.

There's pre-CORS workarounds. You could build an HTML multipart/form-data POST form inside an iframe and submit it with JavaScript for example. And if the server API supports JSONP, you can inject a script tag into your page that loads the target content as a script which then executes the data in a callback to read it back into the client page.

If you don't care about REST, and you only need to do GET/POST requests with a limited set of mime types, you could make a client-side application that gets around the same-origin policy without using CORS. But it's ugly.

With CORS though, you can potentially make any type of request across origins, because the CORS preflight OPTION requests allow a server to specify what request methods and what headers a client from a certain origin can access at a given URI. And these days, you can find CORS-enabled third-party REST APIs that you can use with things like client-side OAuth to provide all the same functionality that you would have in a traditional web applications.

I've been thinking about using a completely split API/client-side app architecture in my own projects lately, because scaling a bare API is much easier and cheaper than scaling a web application.

So yes, CORS is just a security measure, but it gives you more functionality in a client-side application by allowing you to bypass an older security measure, the same-origin policy, in a very clean and explicit way.



Very insightful, again Thanks for all the writing, I'm studying CORS now due to the info you shared :)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: