I am trying to make a stand-alone HTML file that makes cross-domain requests via CORS to a RESTful JSON service.
My jQuery ajax request:
var query = $.ajax( { type: 'GET', url: 'http://localhost:8626/Home/About', contentType: 'application/json', dataType: 'json', success: function (response) { alert('success'); alert(query.getAllResponseHeaders()); alert($.cookie('SessionID')); }, error: function (x, e) { alert('error ' + e); } }); I set the Access-Control-etc headers on the (ASP MVC3) server side:
public ActionResult About() { Response.AddHeader("Access-Control-Allow-Origin", "*"); Response.AddHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE"); Response.AddHeader("Access-Control-Allow-Headers", "Content-Type"); Response.SetCookie(new HttpCookie("SessionID", "1234")); return Json(new { name = "John" }, JsonRequestBehavior.AllowGet); } Apart from cookies, everything works well. I get my response JSON data properly.
But I am also sending a cookie back from the server. It isn't showing in the headers as a Set-Cookie, and it isn't showing in the cookies collection. I have read here that to get cookies in a cross-domain request, you need to set the following in the $.ajax call:
xhrFields: { withCredentials: true }, When I add this, the call no longer works, with a JS error:
Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true. Clearly it is griping about my Access-Control-Allow-Origin header being "*".
Since this is a flat, stand-alone HTML file (sourced from the disk, not from an HTTP server), Chrome is passing along an Origin header equal to "null". I don't appear to be able to override this value -- when I add a custom Origin header, Chrome apparently disregards it.
If I return Access-Control-Allow-Origin = "null" (matching the Origin header value from the request), I get the JS error:
Origin null is not allowed by Access-Control-Allow-Origin. So I don't know what to do. I can't get my cookies with the wildcard, and allowing "null" instead doesn't work either.
Is this not possible? Or am I missing a step?