2

I have frontend running on localhost:9000 and backend on localhost:4567.

 $.post("http://localhost:4567/login",
                {
                    user: u,
                    password: p,
                    crossDomain: true,
                    xhrFields: { withCredentials: true }
                },
                function (data) {
                    window.location.replace("app.html")
                })
                .fail(function (x) {
                    ...
                });

The login request succeeds and server returns

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:*
Access-Control-Allow-Origin:http://localhost:9000
Access-Control-Request-Method:*
Cache-Control:no-cache, no-store, must-revalidate
Content-Length:1
Content-Type:text/html; charset=UTF-8
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Server:Jetty(9.0.z-SNAPSHOT)
Set-Cookie:JSESSIONID=1bput5i7fmccb13o5pe2rop8w0;Path=/

The browser however does not set the cookie and future requests do not have this cookie. Tested on Chrome and Firefox. If front end and backend or on same port, it works fine. So why is cookie not set if I call backend on different port?

Hisham
  • 1,305
  • 2
  • 15
  • 24
  • 2
    Duplicate of [2870371](http://stackoverflow.com/questions/2870371/why-is-jquerys-ajax-method-not-sending-my-session-cookie). From an answer on that page: *"You should use xhrFields param of http://api.jquery.com/jQuery.ajax/"*: `$.ajax( url: ..., xhrFields: { withCredentials: true } )` – Kenney Oct 21 '15 at 22:52
  • thanks that worked! So had to use $.ajax instead of $.post – Hisham Oct 22 '15 at 04:16

1 Answers1

3

Thanks to @Kenney's comment, changing $.post to $.ajax was the fix:

$.ajax(
                        {
                            url: "http://localhost:4567/login",
                            method: "post",
                            data: { user: u, password: p },
                            user: u,
                            password: p,
                            crossDomain: true,
                            xhrFields: { withCredentials: true }
                        }).done(function(data) {
                             window.location.replace("app.html");
                        })
                        .fail(function (x) {
                            ...
                        });
Hisham
  • 1,305
  • 2
  • 15
  • 24