Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

javascript - How to get Expess object cookie in angularJS?

Express documentation says that we can set a cookie with an object using this function:

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

I want to retrieve this value using Angular ngCookie:

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

But it throw an error:

SyntaxError: Unexpected token j

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.

Can I force Express to not set the cookie with this syntax (without "j:")?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can make JSON-string manually:

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

Prefix j: added in ./express/lib/response.js (lines 787-789):

var val = typeof value === 'object'
    ? 'j:' + JSON.stringify(value)
    : String(value);

where value is your object { 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...