Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing Location header on jQuery AJAX POST

I'm performing an AJAX POST with jQuery like so:

self.post = function (path, data) {
    return $.ajax({
        url: this.createUri(path),
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        data: ko.toJSON(data)
    });
};

Here I just return the AJAX Deferred object. The response is handled by another object:

api.post(menuItemsUri, self.newItem)
    .done(function (data, textStatus, request) {
        console.log(request.getResponseHeader("Location")); // undefined
    })
    .always(function () {
        // reset the current item
        self.newItem.update({});
    });

The server returns a 201 Created Response and sets the Location header. I can see this in the Chrome Network tab:

Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:0
Date:Thu, 07 Feb 2013 10:25:04 GMT
Expires:-1
Location:http://localhost:49978/sites/1/menus/65/items/19
Pragma:no-cache

However, the Location header is missing from the XmlHttpRequest object passed in the jQuery AJAX callback.

like image 641
Ben Foster Avatar asked Feb 07 '13 10:02

Ben Foster


1 Answers

The issue was that this was a CORS request and according to the CORS Spec only the following "Simple Response Headers" are exposed:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

To expose additional headers you need to include them in the Access-Control-Expose-Headers header e.g.:

Access-Control-Expose-Headers: location

Once this change was made, the Location header was available to the XmlHttpRequest object via getResponseHeader("Location").

For normal (non-CORS) requests, this is not an issue.

like image 90
Ben Foster Avatar answered Sep 20 '22 23:09

Ben Foster