[英]Accessing nodejs cookies in angularjs
I am building a simple web app using nodejs as backend with angularjs front-end.我正在使用 nodejs 作为后端和 angularjs 前端构建一个简单的 Web 应用程序。
With nodejs I am setting some cookies after a user logs in.使用 nodejs,我在用户登录后设置了一些 cookie。
res.cookie(name,value)
I am creating two cookies each for username and user_id.我正在为 username 和 user_id 创建两个 cookie。 and when I see the set cookies, using
当我看到设置的 cookie 时,使用
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.并且 json 响应具有实际的 user_id 以及另一个键connect.sid ,也许是因为我使用的是 connect-flash,我不知道。
But when I access the cookies in angularjs using $cookies.get('user_id') the value is some encoded value,但是当我使用 $cookies.get('user_id') 访问 angularjs 中的 cookie 时,该值是一些编码值,
For eg : for actual user_id : 571be8d34666cf69664645d5 ,例如:对于实际的 user_id : 571be8d34666cf69664645d5 ,
I am getting j%3A%22571be8d34666cf69664645d5%22我得到j%3A%22571be8d34666cf69664645d5%22
How can I get the actual userid ?我怎样才能获得实际的用户 ID?
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.我知道真正的 ID 在字符串之间,我可以通过使用一些字符串操作来获取它,但是还有另一种方法。
I am using passportjs, express-session, connect-flash, connect-mongo,cookie-parser in my app.我在我的应用程序中使用了passportjs、express-session、connect-flash、connect-mongo、cookie-parser。
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:您可以在 express 的 cookie 中设置对象,而不是使用两个不同的 cookie,而在 angular 方面,您可以通过以下方式获取 cookie:
$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.在您的情况下,要么编写一个用于拆分 cookie 的函数,要么使用
JSON.parse(json)
来解析来自 express 的 cookie。 I did it other way round and managed to read the cookie object in express by JSON.parse(cookieobj.user_id)
我以其他方式完成并设法通过
JSON.parse(cookieobj.user_id)
在 express 中读取 cookie 对象
It seems that as of angular 1.4, you should use $cookies.getObject('user_id')
for deserialize version of the value.似乎从 angular 1.4 开始,您应该使用
$cookies.getObject('user_id')
来反序列化该值的版本。 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.首先,如果不是解决方案,请在控制台上检查 cookie 的实际值,以尝试了解
j:"571be8d34666cf69664645d5"
来源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.