Cookies on localhost with explicit domain

前端 未结 21 1828
[愿得一人]
[愿得一人] 2020-11-22 04:17

I must be missing some basic thing about cookies. On localhost, when I set a cookie on server side and specify the domain explicitly as localhost (or .localhost). t

21条回答
  •  别那么骄傲
    2020-11-22 05:05

    None of the suggested fixes worked for me - setting it to null, false, adding two dots, etc - didn't work.

    In the end, I just removed the domain from the cookie if it is localhost and that now works for me in Chrome 38.

    Previous code (did not work):

    document.cookie = encodeURI(key) + '=' + encodeURI(value) + ';domain=.' + document.domain + ';path=/;';
    

    New code (now working):

     if(document.domain === 'localhost') {
            document.cookie = encodeURI(key) + '=' + encodeURI(value) + ';path=/;' ;
        } else {
            document.cookie = encodeURI(key) + '=' + encodeURI(value) + ';domain=.' + document.domain + ';path=/;';
        }
    

提交回复
热议问题