如何获取Expess对象cookie在angularJS? [英] How to get Expess object cookie in angularJS?
问题描述
快速文档说,我们可以使用此对象设置一个包含对象的Cookie函数:
Express documentation says that we can set a cookie with an object using this function:
res.cookie('cart', { items: [1,2,3] });
我要使用 Angular ngCookie :
var cart= $cookies.getObject('cart');
但它会抛出一个错误:
SyntaxError: Unexpected token j
我可以检索字符串值该cookie使用 $ cookie.get('cart')
,确实,它看起来像这样:
I can retrieve the string value of the cookie using $cookie.get('cart')
, and, indeed, it looks like this:
j:{ "items": [1,2,3] }
我知道我可以删除字符,然后解析对象,但我宁愿有一个更通用的方法。
I know I can remove the characters and then parse the object, but I'd rather have a more generic method.
我可以强制Express
Can I force Express to not set the cookie with this syntax (without "j:")?
推荐答案
您可以使用JSON-字符串手动:
You can make JSON-string manually:
res.cookie('cart', JSON.stringify({ items: [1,2,3] }) );
前缀 j:
$ c> ./ express / lib / response.js (第787-789行):
Prefix j:
added in ./express/lib/response.js
(lines 787-789):
var val = typeof value === 'object'
? 'j:' + JSON.stringify(value)
: String(value);
其中 value
是您的对象 {items:[1,2,3]}
因为Cookie的RFC说的值只能是一个字符串。理想情况下,如果我们遵循标准,如果不是字符串,我们将拒绝您的cookie。为了方便起见,Express.js允许你设置非字符串作为值,我们将JSON.stringify值,pre-pending aj:所以我们知道当我们再次读取它的时候,值应该是JSON.parsed 。
It's not part of any standard, as the RFC for cookies says the value can only be a string. Ideally if we followed the standard, we would reject your cookie if it wasn't a string. As a convenience, Express.js allows you to set non-strings as the values, and we'll JSON.stringify the value, pre-pending a j: so we know the value should be JSON.parsed when we read it again for you.
https://github.com/expressjs/express/issues/2815
这篇关于如何获取Expess对象cookie在angularJS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!