stevermeister / ngx-cookie-service

Angular (4.2+ ...12) service for cookies. Originally based on the `ng2-cookies` library.
https://www.npmjs.com/package/ngx-cookie-service
MIT License
544 stars 89 forks source link

Cookies not getting set #28

Closed nicolaspierre1990 closed 6 years ago

nicolaspierre1990 commented 6 years ago

Expected Behavior

Cookie being set

Actual Behavior

No cookie being set

Steps to Reproduce the Problem

What i'm trying to do is to store a JWT token in a cookie using following code. ` setCookie(name: string, value: string, encrypt: boolean, days?: number) { let date = null; if (days) { date = new Date(); date.setTime(date.getTime() + (days 24 60 60 1000)); }

    if(encrypt){
        value = btoa(value);
    }

    this.cookie.set(name, value, date, "/", environment.domain, true);
}`

but the cookie is not getting created. I stept into the code of the plugin and no errors happen there.

Specifications

andreas-harmuth commented 6 years ago

I have the same problem with same specifications.

phoude commented 6 years ago

I have problem where cookie values are not persisted in IE or Edge. Still investigating what could be causing it...

UPDATE: I have found the cause of my issue. I was not setting the path when setting the cookie. In Chrome it was setting the root path and the page specific path where the cookie was set from (why both). In IE, it was doing only the latter. I am not sure what is the expected behavior when not specifying the path but it is strange the behavior is different from IE than other browsers.

phoude commented 6 years ago

I have done further testing and it looks like there is an inherent problem with how cookies are read back when used in conjunction with an Angular router. I don't know how to resolve this other than by explicitly setting the path to "/". It does not work otherwise with a different path as described in my stackoverflow post.

azhararmar commented 5 years ago

Same here with Angular7, it works when the path is set to "/" otherwise it doesn't

cyphercodes96 commented 5 years ago

Same here, been facing this issue recently with .localhost as domain this.cookieService.set('currentUser_email', email, undefined, '/', '.' + cookieDomain.toString()); console.log(cookieDomain.toString()); // localhost, attempting to set domain to .localhost console.log(this.cookieService.getAll()); // {} empty object console.log(this.cookieService.check('currentUser_id')); // false

Shubham-Kul commented 5 years ago

just do like this this.cookieService.set('categoryName', category.name, 365, '/'); key = 'categoryName', value = 'category.name', expire = 365 days, path = '/' It will solve your problem