简体   繁体   English

在express.js中设置cookie出现j:前缀

[英]Set cookie in express.js appear j: prefix

I'm trying to set cookie using res.cookie like below: 我正在尝试使用res.cookie设置cookie,如下所示:

res.cookie('userId',req.user._id); //set cookie here
console.log(req.user._id); //returned correct value, eg abc

then I'm seeing j:"abc" in my cookie, why does this happens? 然后我在我的cookie中看到j:“abc”,为什么会发生这种情况?

I know this is a bit late, but I came across this issue myself and have been digging around a bit. 我知道这有点晚了,但我自己也遇到了这个问题并且一直在挖掘。 It seems they're prefixing any JSON strings with "j:" so they know it's a JSON string when parsing it back. 看起来他们用“j:”为任何JSON字符串添加前缀,因此他们知道在解析它时它是一个JSON字符串。 What this basically means is that you have to manually remove the "j:" if you're using some other way of parsing it. 这基本上意味着你必须手动删除“j:”,如果你正在使用其他方式解析它。

Cookies are encrypted to the client side. Cookie被加密到客户端。 You need a cookie-parser to correctly get the user.id from your cookie. 您需要一个cookie解析器才能从您的cookie中正确获取user.id. See its documentation for use. 请参阅其文档以供使用。

According the the Express 4 docs , res.cookie(name, value [, options]) sets a cookie name to a value. 根据Express 4文档res.cookie(name, value [, options])将cookie名称设置为值。 The value parameter may be a string or object converted to JSON. value参数可以是转换为JSON的字符串或对象。

In this instance, req.user._id is an object so you would set the cookie as res.cookie('userId', JSON.stringify(req.user._id)) 在这个例子中, req.user._id是一个对象,因此您可以将cookie设置为res.cookie('userId', JSON.stringify(req.user._id))

So I'm using cookie-parser & express-session on the NodeJS side, ng2-cookies on the client side. 所以我在NodeJS端使用cookie-parser和express-session,在客户端使用ng2-cookies。 I was also expecting to read userId as ie 59bca61b74d1cac10ce50d0c rather than j:59bca61b74d1cac10ce50d0c :( 我也期待读取userId为59bca61b74d1cac10ce50d0c而不是j:59bca61b74d1cac10ce50d0c :(

So, rather than have to do some magic on the client side I just did res.cookie('cookieName', cookieValue.toString(), cookieOptions) and this gave me what I was looking for. 所以,不要在客户端做一些魔术我只是做了res.cookie('cookieName', cookieValue.toString(), cookieOptions) ,这给了我正在寻找的东西。

Doing a console.log('cookies', req.cookies) shows things are fine, although req.headers.cookie shows 2 userId cookies (still testing) 做一个console.log('cookies', req.cookies)显示一切正常,虽然req.headers.cookie显示2个userId cookies(仍在测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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