重新启动浏览器后,angular ngCookies不会保存cookie

时间:2016-09-24 11:50:05

标签: javascript angularjs node.js cookies angular-cookies

 var app = angular.module('MyApp', ['ngCookies']);
        app.controller('MyController', function ($scope, $window, $cookies) {
            $scope.WriteCookie = function () {
                $cookies.put("Name", $scope.Name);

            };
            $scope.ReadCookie = function () {
                $window.alert($cookies.get('Name'));
            };
            $scope.RemoveCookie = function () {
                $cookies.remove('Name');
            };
        });
<html>
<head>
    <title></title>
</head>
<body>
  <div ng-app="MyApp" ng-controller="MyController">
        Name:
        <input type="text" ng-model="Name" />
        <br />
        <br />
        <input type="button" value="Write Cookie" ng-click="WriteCookie()" />
        <input type="button" value="Read Cookie" ng-click="ReadCookie()" />
        <input type="button" value="Remove Cookie" ng-click="RemoveCookie()" />
    </div>
</body>
</html>

我用角度写了这个简单的demp app for cookies。

每当我输入此内容(通过nodeJS)并转到此网址:http://127.0.0.1:8080

Cookie已在浏览器的Cookie中提供。当我点击刷新或关闭标签并打开带有此网址的新标签(不关闭浏览器)时,Cookie会保留。

但是,当我关闭浏览器(chrome / IE / firefox)并再次打开此URL时,cookie就不存在了!

为什么呢?我怎么能像facebook一样,即使我从电脑上取下电脑并再次启动它,它还能记住我的登录信息吗?

谢谢

的index.html

<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-cookies.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', ['ngCookies']);
        app.controller('MyController', function ($scope, $window, $cookies) {
            $scope.WriteCookie = function () {
                $cookies.put("Name", $scope.Name);

            };
            $scope.ReadCookie = function () {
                $window.alert($cookies.get('Name'));
            };
            $scope.RemoveCookie = function () {
                $cookies.remove('Name');
            };
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        Name:
        <input type="text" ng-model="Name" />
        <br />
        <br />
        <input type="button" value="Write Cookie" ng-click="WriteCookie()" />
        <input type="button" value="Read Cookie" ng-click="ReadCookie()" />
        <input type="button" value="Remove Cookie" ng-click="RemoveCookie()" />
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

这是因为如果您没有为Cookie设置过期时间,则会将其创建为会话Cookie。关闭浏览器后将立即将其删除。

为了避免这种情况,只需设置Cookie的过期时间,例如这里有一天:

var expireDate = new Date(); 
expireDate.setDate(expireDate.getDate() + 1); 

$cookies.put('Name', $scope.Name, {
  expires: expireDate
});