What can cause a cookie not to be set on the client?

后端 未结 3 852
抹茶落季
抹茶落季 2020-12-15 23:12

I have a web application that uses jQuery.ajax to perform a request to another host (right now actually the same because I\'m using different ports of \"localhost\"). The se

相关标签:
3条回答
  • 2020-12-15 23:35

    I think I found the solution. Since during development, my server is at "localhost:30002" and my web app at "localhost:8003", they are considered different hosts regarding CORS. Therefore, all my requests to the server are covered by CORS security rules, especially Requests with credentials. "Credentials" include cookies as noted on that link, so the returned cookie was not accepted because I did not pass

    xhrFields: {
      withCredentials: true
    }
    

    to jQuery's $.ajax function. I also have to pass that option to subsequent CORS requests in order to send the cookie.

    I added the header Access-Control-Allow-Credentials: true on the server side and changed the Access-Control-Allow-Origin header from wildcard to http://localhost:8003 (port number is significant!). That solution now works for me and the cookie gets stored.

    0 讨论(0)
  • 2020-12-15 23:52

    After struggling with a similar scenario (no CORS) for hours, I found out another potential reason: be sure to explicitly set the path for the cookie.

    My front-end app was making a call to HOST_URL/api/members/login, and this was returning the right Set-Cookie header, with no path.

    I could see the cookie under Response Cookies in Chrome DevTools, but subsequent requests were not including it. Went to chrome://settings/cookies, and the cookie was there, but the path was /api/members.

    Specifying root path when setting the cookie at server-side fixed the issue.

    0 讨论(0)
  • 2020-12-15 23:54

    where do you get the date from?

    if you add it manually try making it failproof

    var exdays = 3; //3 days valid as an example
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    //Now set the cookie to said exdate
    document.cookie = "MyUserSession =" + escape(JxQoyzYm1VfESmuh-v22wyiyLREyOkuQWauziTrimjKo=)+"; expires="+exdate.toUTCString());
    
    0 讨论(0)
提交回复
热议问题