ton ton - 5 months ago 83
Ajax Question

Get and store cookie (from Set-Cookie) from an AJAX POST response

I have a simple jQuery AJAX POST code:

$.ajax({
type: "POST",
url: AppConstants.URLs.PROXY,
data: message,
xhrFields: {
withCredentials: true
},
success: function(data, status, xhr) {
console.log("Cookie: " + xhr.getResponseHeader("Set-Cookie"));
}
});


and I wish to get the cookie and save it using cookies-js.

But according to http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders%28%29-method:



  1. Return all response headers, excluding headers that are a case-insensitive match for Set-Cookie or Set-Cookie2, as a single string, with each header line separated by a U+000D CR U+000A LF pair, excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE pair.




Using the Network tool in Chrome, "Set-Cookie" is visible in the Response headers. I also verified that the "Set-Cookie" header appears using
curl
.

What do I have to do to save the cookie in my front end app? Also, my app is running on https only.

I'd gladly provide more details upon request.

Answer

You can't get the cookie data in your JS. The API won't allow you.

What do I have to do to save the cookie in my front end app?

Just set send the Set-Cookie header from the server side code. The browser should save it automatically.