I\'m developing a jQuery plug-in that will be a connector for some REST API. The implementation is straight forward, but the same origin policy is definitely painfull. I nee
It's a bit of a fiddle sometimes, some thoughts:
XMLHttpRequest
object, but jQuery doesn't specifically cater for that (yet; I have to admit I'm slightly surprised and Access-Control-Allow-Origin
value? It looks like it's only allowing access from the server it's on. That header is meant to specify what origins the server will allow the request to come from. (And *
is allowed, to mean "anywhere.")OPTIONS
request that it hadn't asked for.x-requested-with
), but I bet there will be others in the actual request.FWIW (I'm not a Python guy), here's my JSP code that works, perhaps it will be useful — I think the object names are clear enough to be readable even if you don't do Java (and who knows, maybe you do):
String corsOrigin, corsMethod, corsHeaders;
// Find out what the request is asking for
corsOrigin = request.getHeader("Origin");
corsMethod = request.getHeader("Access-Control-Request-Method");
corsHeaders = request.getHeader("Access-Control-Request-Headers");
if (corsOrigin == null || corsOrigin.equals("null")) {
// Requests from a `file://` path seem to come through without an
// origin or with "null" (literally) as the origin.
// In my case, for testing, I wanted to allow those and so I output
// "*", but you may want to go another way.
corsOrigin = "*";
}
// Add headers allowing specifically what was requested
response.addHeader("Access-Control-Allow-Origin", corsOrigin);
response.addHeader("Access-Control-Allow-Methods", corsMethod);
response.addHeader("Access-Control-Allow-Headers", corsHeaders);
if (request.getMethod().equals("OPTIONS"))
{
// Done, no body in response to OPTIONS
return;
}
// Processing the GET or POST here; output the body of the response
Note that I'm using exactly the same logic for GET
, POST
, and OPTIONS
except that in the case of OPTIONS, I don't output a response body.