简体   繁体   中英

Accessing nodejs cookies in angularjs

I am building a simple web app using nodejs as backend with angularjs front-end.

With nodejs I am setting some cookies after a user logs in.

res.cookie(name,value)

I am creating two cookies each for username and user_id. and when I see the set cookies, using

res.json(req.cookies)

and the json response have the actual user_id and also with a another key connect.sid , maybe because I am using connect-flash, I don't know.

But when I access the cookies in angularjs using $cookies.get('user_id') the value is some encoded value,

For eg : for actual user_id : 571be8d34666cf69664645d5 ,

I am getting j%3A%22571be8d34666cf69664645d5%22

How can I get the actual userid ?

I know that the real ID is in between the string and I can get it by using some string manipulation, but is there another way.

I am using passportjs, express-session, connect-flash, connect-mongo,cookie-parser in my app.

Instead of using two different cookies, you can set the object in the cookie from express, and on angular side you can get the cookies by:

$cookies.getObject('cookiename',object)

In your case either write a function for splitting the cookie or use JSON.parse(json) for parsing the cookie coming from express. I did it other way round and managed to read the cookie object in express by JSON.parse(cookieobj.user_id)

It seems that as of angular 1.4, you should use $cookies.getObject('user_id') for deserialize version of the value. Start with that, if not a solution, check on the console the actual value of the cookie to try to understand where the j:"571be8d34666cf69664645d5" come from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM