javascript - 如何在 angularJS 中获取 Expess 对象 cookie?

标签 javascript angularjs express cookies

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.

https://github.com/expressjs/express/issues/2815

关于javascript - 如何在 angularJS 中获取 Expess 对象 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35085674/

相关文章:

javascript - 未捕获错误 : Syntax error, 无法识别的表达式:# Something

javascript - 匹配 JSON 对象中的键/值

javascript - Bootstrap 4 移动/桌面页面布局隐藏在带有标题的移动设备上的两个侧边栏

ruby-on-rails - rails 中 link_to 内的 Angular 表达式

angularjs - ng-repeat指令的 `priority`是什么,你能改变它吗?

node.js - 避免使用 localhost 来解析 mocha 中的测试

javascript - 在 React 中点击可点击组件的外部

angularjs - ng-Map 未在信息窗口中显示文本

javascript - 一个简单的 Node/快速获取请求和响应

node.js - ExpressJs 在生产模式下不缓存 View