Express documentation说我们可以使用这个函数用一个对象设置一个 cookie:
res.cookie('cart', { items: [1,2,3] });
我想使用 Angular ngCookie 检索此值:
var cart= $cookies.getObject('cart');
但是它抛出一个错误:
SyntaxError: Unexpected token j
我可以使用 $cookie.get('cart')
检索 cookie 的字符串值,实际上,它看起来像这样:
j:{ "items": [1,2,3] }
我知道我可以删除字符然后解析对象,但我宁愿使用更通用的方法。
我可以强制 Express 不使用这种语法(没有“j:”)设置 cookie 吗?
最佳答案
您可以手动制作 JSON 字符串:
res.cookie('cart', JSON.stringify({ items: [1,2,3] }) );
前缀 j:
添加到 ./express/lib/response.js
(第 787-789 行):
var val = typeof value === 'object'
? 'j:' + JSON.stringify(value)
: String(value);
value
是你的对象 { items: [1,2,3] }
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.
关于javascript - 如何在 angularJS 中获取 Expess 对象 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35085674/