gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:46:28 25 4
gpt4 key购买 nike

 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>

我用 angular 为 cookie 编写了这个简单的 demp 应用程序。

每当我输入这个(通过 nodeJS)并转到这个 url:http://127.0.0.1:8080

cookie 保存在浏览器的 cookie 中。当我单击刷新或关闭选项卡并使用此 url 打开一个新选项卡(不关闭浏览器)时,cookie 会保留。

但是,当我关闭浏览器(chrome/IE/firefox)并再次打开这个 url 时,cookies 不存在了!

为什么?我怎样才能让它像 facebook 一样,即使我关闭我的电脑并重新启动它也会记住我的 coockis 登录信息?

谢谢

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>

最佳答案

这是因为如果您不为 cookie 设置过期时间,它将被创建为 session cookie。一旦您关闭浏览器,它就会被删除。

为了避免这种情况,只需为 cookie 设置一个过期时间,例如在这里待一天:

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

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

关于javascript - 重新启动浏览器后,angular ngCookies 不保存 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39676010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com