如何在 angularJS 中获取 Expess 对象 cookie? [英] How to get Expess object cookie in angularJS?

查看:29
本文介绍了如何在 angularJS 中获取 Expess 对象 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Express 文档 说我们可以使用这个对象设置 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 检索此值:

I want to retrieve this value using Angular ngCookie:

var cart= $cookies.getObject('cart');

但它抛出一个错误:

SyntaxError: Unexpected token j

我可以使用 $cookie.get('cart') 检索 cookie 的字符串值,实际上,它看起来像这样:

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 不使用这种语法(没有j:")设置 cookie 吗?

推荐答案

您可以手动制作 JSON-string:

You can make JSON-string manually:

res.cookie('cart', JSON.stringify({ items: [1,2,3] }) );

前缀 j: 添加到 ./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 值,前置 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

这篇关于如何在 angularJS 中获取 Expess 对象 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆