Cookies on localhost with explicit domain

前端 未结 21 1811
[愿得一人]
[愿得一人] 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:02

    If you're setting a cookie from another domain (ie you set the cookie by making an XHR cross origin request), then you need to make sure you set the withCredentials attribute to true on the XMLHttpRequest you use to fetch the cookie as described here

    0 讨论(0)
  • 2020-11-22 05:02

    I had much better luck testing locally using 127.0.0.1 as the domain. I'm not sure why, but I had mixed results with localhost and .localhost, etc.

    0 讨论(0)
  • 2020-11-22 05:02

    None of the answers here worked for me. I fixed it by putting my PHP as the very very first thing in the page.

    Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

    From http://php.net/manual/en/function.setcookie.php

    0 讨论(0)
  • 2020-11-22 05:03

    localhost: You can use: domain: ".app.localhost" and it will work. The 'domain' parameter needs 1 or more dots in the domain name for setting cookies. Then you can have sessions working across localhost subdomains such as: api.app.localhost:3000.

    0 讨论(0)
  • 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=/;';
        }
    
    0 讨论(0)
  • 2020-11-22 05:06

    There is an issue on Chromium open since 2011, that if you are explicitly setting the domain as 'localhost', you should set it as false or undefined.

    0 讨论(0)
提交回复
热议问题