【发布时间】:2015-11-18 09:21:24
【问题描述】:
我在 Cookie 上存储了一个用户对象,当客户端再次访问该站点时,我想使用该对象的属性。
但是,当客户端返回时,我的 cookie 对象看起来像 [object object],而它的属性看起来像 undefined。
这是我的代码:
$scope.signup = function (user) {
$http.post('/api/signup', user)
.then( function (res) {
$cookies.put('user', res.data.user); //This is where I store my cookie.
}, function (res) {
});
};
当客户回来时,我有这段代码:
var lastUser = $cookies.get('user');
if (lastUser) $scope.lastName = lastUser.username;
console.log(lastUser); // [object object]
console.log(lastName); // undefined
如何正确获取 cookie 信息?
【问题讨论】:
-
cookie 来存储一个对象是个坏主意。使用本地存储。
-
感谢您的回答。请告诉我为什么?
-
谢谢,@epascarello 我会读的。
-
Cookies 只存储字符串,不存储对象。因此,在将数据放入 cookie 之前,您必须将数据转换为字符串形式。如果您的数据不是简单的字符串或数字,您可以在对象上使用
JSON.stringify()。
标签: javascript angularjs node.js cookies npm