Get and save cookie (from Set-Cookie) from 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 want to get a cookie and save it using cookies-js .

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

  1. Returns all response headers , excluding case- insensitive headers for Set-Cookie or Set-Cookie2 , as one line, each header line is separated by U + 000D CR U + 000A LF, with the exception of the status line, and with each header and value header, separated by a pair of COSION U + 0020 U + 003A.

Using the Network tool in Chrome, the Set-Cookie appears in the response headers. I also confirmed that the "Set-Cookie" header appears using curl .

What do I need to do to save a cookie in my front-end application? In addition, my application only works on https .

I would gladly provide more detailed information upon request.

+6
source share
2 answers

You cannot receive cookies in your JS. The API will not allow you.

What do I need to do to save a cookie in my front-end application?

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

As a developer, you can check the value of cookies using the "Developer Tools".

And the same cookie will be sent in subsequent requests to the same domain until the cookie expires.

+10
source

The browser cannot provide access to third-party cookies, such as those obtained from ajax requests for security reasons, however , it takes care of them automatically for you!

For this you need:

1) log in with ajax request from which you expect cookies to be returned:

 $.ajax("https://example.com/v2/login", { method: 'POST', data: {login_id: user, password: password}, crossDomain: true, success: login_success, error: login_error }); 

2) Connect with xhrFields: { withCredentials: true } in the following ajax request (s) to use the credentials stored by the browser

 $.ajax("https://example.com/v2/whatever", { method: 'GET', xhrFields: { withCredentials: true }, crossDomain: true, success: whatever_success, error: whatever_error }); 

The browser takes over these cookies for you, although they are not readable from headers and document.cookie

see my answer here: How to get a cookie from an AJAX response?

+5
source

Source: https://habr.com/ru/post/986054/


All Articles