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.
The issue was that this was a CORS request and according to the CORS Spec only the following "Simple Response Headers" are exposed:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With