Javascript 如何在 AngularJS 中设置 cookie 的过期日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12624181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:52:30  来源:igfitidea点击:

How to set expiration date for cookie in AngularJS

javascriptcookiesangularjssession-cookiesangular-cookies

提问by Anand

  1. We want to store User's Authorization information in cookie which should not be lost upon refresh (F5) of browser.

  2. We want to store authorization info in "permanent-cookie" in case user has opted for "Remember Me" check box at the time of log-on.

  1. 我们希望将用户的授权信息存储在 cookie 中,该信息在浏览器刷新 (F5) 时不应丢失。

  2. 我们希望将授权信息存储在“永久cookie”中,以防用户在登录时选择了“记住我”复选框。

回答by Geert van Dort

This is possible in the 1.4.0 build of angular using the ngCookiesmodule:

这在使用ngCookies模块的 1.4.0 构建中是可能的:

https://docs.angularjs.org/api/ngCookies/service/$cookies

https://docs.angularjs.org/api/ngCookies/service/$cookies

angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
  // Find tomorrow's date.
  var expireDate = new Date();
  expireDate.setDate(expireDate.getDate() + 1);
  // Setting a cookie
  $cookies.put('myFavorite', 'oatmeal', {'expires': expireDate});
}]);

回答by streetlogics

For 1.4: As noted in the comment here and others below, as of 1.4, Angular's native cookie support now provides the ability to edit cookies:

对于 1.4:正如此处和下面其他评论中所述,从 1.4 开始,Angular 的本机 cookie 支持现在提供了编辑 cookie 的能力:

Due to 38fbe3ee, $cookies will no longer expose properties that represent the current browser cookie values. $cookies no longer polls the browser for changes to the cookies and no longer copies cookie values onto the $cookies object.

This was changed because the polling is expensive and caused issues with the $cookies properties not synchronizing correctly with the actual browser cookie values (The reason the polling was originally added was to allow communication between different tabs, but there are better ways to do this today, for example localStorage.)

The new API on $cookies is as follows:

get put getObject putObject getAll remove You must explictly use the methods above in order to access cookie data. This also means that you can no longer watch the properties on $cookies to detect changes that occur on the browsers cookies.

This feature is generally only needed if a 3rd party library was programmatically changing the cookies at runtime. If you rely on this then you must either write code that can react to the 3rd party library making the changes to cookies or implement your own polling mechanism.

由于 38fbe3ee,$cookies 将不再公开表示当前浏览器 cookie 值的属性。$cookies 不再轮询浏览器对 cookie 的更改,也不再将 cookie 值复制到 $cookies 对象上。

这已更改,因为轮询成本高昂,并导致 $cookies 属性无法与实际浏览器 cookie 值正确同步的问题(最初添加轮询的原因是为了允许不同选项卡之间的通信,但今天有更好的方法来做到这一点,例如 localStorage。)

$cookies 上的新 API 如下:

get put getObject putObject getAll remove 您必须明确使用上述方法才能访问 cookie 数据。这也意味着您不能再通过查看 $cookies 的属性来检测浏览器 cookie 上发生的更改。

通常仅当第 3 方库在运行时以编程方式更改 cookie 时才需要此功能。如果您依赖于此,那么您必须编写可以对 3rd 方库对 cookie 进行更改做出反应的代码,或者实现您自己的轮询机制。

The actual implementation is done via a $cookiesProviderobject, which can be passed via the putcall.

实际的实现是通过$cookiesProvider对象完成的,该对象可以通过put调用传递。

For 1.3 and below: For those of you who have done your best to avoid having to load jQuery plugins, this appears to be a nice replacement for angular - https://github.com/ivpusic/angular-cookie

对于 1.3 及以下版本:对于那些尽力避免加载 jQuery 插件的人来说,这似乎是 angular 的一个不错的替代品 - https://github.com/ivpusic/angular-cookie

回答by Nobita

In Angular v1.4 you can finallyset some options for the cookies, such as the expiration. Here's a very simple example:

在 Angular v1.4 中,您终于可以为 cookie 设置一些选项,例如过期时间。这是一个非常简单的例子:

var now = new Date(),
    // this will set the expiration to 12 months
    exp = new Date(now.getFullYear()+1, now.getMonth(), now.getDate());

$cookies.put('someToken','blabla',{
  expires: exp
});

var cookie = $cookies.get('someToken');
console.log(cookie); // logs 'blabla'

If you check your cookies after running this code you will see that the expiration will be properly set to the cookie named someToken.

如果您在运行此代码后检查您的 cookie,您将看到过期时间将正确设置为名为 的 cookie someToken

The object passed as a third param to the putfunction above allows for other options as well, such as setting path, domainand secure. Check the docsfor an overview.

作为第三PARAM到传递的对象put上述功能允许其他选项,以及,诸如设置pathdomainsecure。检查文档以获得概述。

PS- As a side note if you are upgrading mind that $cookieStorehas been deprecated, so $cookiesis now the only method to deal with cookies. see docs

PS- 附带说明,如果您要升级$cookieStore已弃用的 Mind,那么$cookies现在是处理 cookie 的唯一方法。查看文档

回答by Andreas Panagiotidis

I would like to present an extra example as some people know the extra duration of the cookies lifetime. ie. They want to set a cookie to last 10 more minutes, or 1 more day.

我想提供一个额外的例子,因为有些人知道 cookie 生命周期的额外持续时间。IE。他们想将 cookie 设置为多持续 10 分钟,或多 1 天。

Usually you already know how much longer the cookie will last in seconds.

通常,您已经知道 cookie 将在几秒钟内持续多长时间。

    var today = new Date();
    var expiresValue = new Date(today);

    //Set 'expires' option in 1 minute
    expiresValue.setMinutes(today.getMinutes() + 1); 

    //Set 'expires' option in 2 hours
    expiresValue.setMinutes(today.getMinutes() + 120); 


    //Set 'expires' option in (60 x 60) seconds = 1 hour
    expiresValue.setSeconds(today.getSeconds() + 3600); 

    //Set 'expires' option in (12 x 60 x 60) = 43200 seconds = 12 hours
    expiresValue.setSeconds(today.getSeconds() + 43200); 

    $cookies.putObject('myCookiesName', 'myCookiesValue',  {'expires' : expiresValue});

and you can retrieve it as usual:

你可以像往常一样检索它:

    var myCookiesValue = $cookies.getObject('myCookiesName');

If empty, it returns undefined.

如果为空,则返回 undefined。

Links;

链接;

http://www.w3schools.com/jsref/jsref_obj_date.asp
https://docs.angularjs.org/api/ngCookies/provider/$cookiesProvider#defaults

http://www.w3schools.com/jsref/jsref_obj_date.asp
https://docs.angularjs.org/api/ngCookies/provider/$cookiesProvider#defaults

回答by yonia

You can go to the angular.js script and change the insert cookie
search for self.cookies = function(name, value) {then u can change the code that adds the cookie for example for 7 days

您可以转到 angular.js 脚本并更改插入 cookie
搜索,self.cookies = function(name, value) {然后您可以更改添加 cookie 的代码,例如 7 天

 if (value === undefined) {
    rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
                            ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  } else {
    if (isString(value)) {
        var now = new Date();
        var time = now.getTime();
        time += 24*60*60*1000*7;
        now.setTime(time);
         cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
                 ';path=' + cookiePath+";expires="+now.toGMTString()).length + 1

回答by Paulo Oliveira

I know that this question is a little bit old, and already have an accepted answer.

我知道这个问题有点老了,并且已经有一个公认的答案。

But still a present problem which I 'm struggling with (not regarding jQuery or pure Javascript).

但仍然是我正在努力解决的当前问题(与 jQuery 或纯 Javascript 无关)。

So, after some research I have found this: https://github.com/ivpusic/angular-cookie

所以,经过一些研究,我发现了这个:https: //github.com/ivpusic/angular-cookie

Which delivers an "interface" quite similar to $cookieStore. And permits to configure the expiration date (value and units).

它提供了一个与 $cookieStore 非常相似的“接口”。并允许配置到期日期(值和单位)。

About angular native support on the expiration date with $cookie or $cookieStore, "they" promise updates on this subject on 1.4, look into this: https://github.com/angular/angular.js/pull/10530

关于 $cookie 或 $cookieStore 到期日的 Angular 本机支持,“他们”承诺在 1.4 上对此主题进行更新,请查看:https: //github.com/angular/angular.js/pull/10530

It will be possible to set expiration date with $cookieStore.put(...), at least they propose that...

可以使用 $cookieStore.put(...) 设置到期日期,至少他们建议...

EDIT:I encountered a "problem" you cannot mix $cookies with angular-cookie modular. So if you set a cookie withipCookie(...)retrieve it with ipCookie(...)because with $cookie it will return undefined.

编辑:我遇到了一个“问题”,你不能将 $cookies 与 angular-cookie 模块混合。因此,如果您设置 cookie 并使用ipCookie(...)检索它,ipCookie(...)因为使用 $cookie 它将返回undefined.

回答by Jan Molak

As @vincent-briglia pointed out, there's a jQuery drop-in that can be used as a workaround until $cookieservice becomes configurable - check it out here

正如@vincent-briglia指出的那样,有一个 jQuery 插件可以用作解决方法,直到$cookie服务变得可配置 -请在此处查看

回答by Andy M.

You may use https://github.com/ivpusic/angular-cookie

您可以使用https://github.com/ivpusic/angular-cookie

First you need to inject ipCookie into your angular module.

首先,您需要将 ipCookie 注入到 angular 模块中。

var myApp = angular.module('myApp', ['ipCookie']);

And now, for example if you want to use it from your controller

现在,例如,如果您想从控制器中使用它

myApp.controller('cookieController', ['$scope', 'ipCookie', function($scope, ipCookie) {
  // your code here
}]);

To create a cookie use

创建 cookie 使用

ipCookie(key, value);

The value supports strings, numbers, booleans, arrays and objects and will be automatically serialized into the cookie.

该值支持字符串、数字、布尔值、数组和对象,并将自动序列化到 cookie 中。

You can also set some additional options, like number of day when a cookie expires

您还可以设置一些附加选项,例如 cookie 过期的天数

ipCookie(key, value, { expires: 21 });