My colleague told me that there is a chrome extension enables you do cross domain request for all sites. Was a bit surprised since my previous understanding was CORS is controlled from the server side with some control headers. So I decided to dig more to it. After reading wiki, and some Chinese article, I think I know how that works.
Overview
One thing I found out is CORS is actually controlled by both server and client side, I mean CORS requires support from both browser and server. All the modern browser and IE 10+ are good to go. The whole process is handled by browser. So for USER, it is transparent. For DEVELOPER, the code is the same. Browser will add some header and sometimes add an extra request.
Two types of Request(Simple/Non-simple)
A simple cross-site request is one that meets all the following conditions:
- The only allowed methods are:
GET
HEAD
POST
- Apart from the headers set automatically by the user agent (e.g.
Connection
,User-Agent
, etc.), the only headers which are allowed to be manually set are:Accept
Accept-Language
Content-Language
Content-Type
- The only allowed values for the
Content-Type
header are:application/x-www-form-urlencoded
multipart/form-data
text/plain
For simple requests, browser will add origin header to the request and see how server response. One caveat is, even if server does not allow, the response status code will probably still be 200. The error can be handled by the onError();
For non-simple requests, browser will send a preflight
request by the OPTIONS
method to the resource on the other domain to see whether it is allowed. According to the previous request definition, the typical xhr json content type(application/json
) is non-simple request which will require a preflight.
chrome CORS extension
So I think how the chrome extension works is it would intercept all the cross site xhr requests.
For simple request, it after getting the response, it would add `Access-Control-Allow-Origin: *
to the header, so that the browser does not complain.
For non-simple request, it would directly return Access-Control-Allow-Origin: *
for the preflight request so that browser will allow the subsequence ‘real’ request to be sent out. One thing I notice is that it will set the Origin to evil.com
which is kind of funny.