【问题标题】:Angular 8 - Clear cookies using CookieServiceAngular 8 - 使用 CookieService 清除 cookie
【发布时间】:2020-03-29 06:31:52
【问题描述】:

我正在尝试清除我的应用保存在浏览器中的所有信息,无论是在 sessionStorage、localStorage 还是 cookie 中。

为此,我添加了这个小方法,它在我的一个组件的ngOnInit 中被调用:

export class SomeComponent implements OnInit {

    constructor(private cookieService: CookieService) {}

    ngOnInit(): void {
        this.clearAppData();
    }

    private clearAppData(): void {
        sessionStorage.clear();
        localStorage.clear();
        this.cookieService.deleteAll();
}

sessionStorage 和 localStorage 似乎已被清除,但我可以看到 cookie 没有。 我需要通过浏览器手动清除cookies。

而且,有时我看到cookie保存在根路径下,有时我看到它在相对根路径下。我不确定这是什么原因,而且有时它会发送错误的 cookie,我想在获取新的 cookie 之前清除所有内容。

任何建议我做错了什么? 谢谢!

【问题讨论】:

  • 使用 CookieService 编辑问题

标签: angular cookies jsessionid


【解决方案1】:

我也面临同样的问题。 如果您的 cookie 是自定义的,这意味着安全、严格、路径,那么您需要使用规范清除。

this._cookieService.delete("cookie name","/","domain name",true,"None");

我相信这对你有用。

【讨论】:

    【解决方案2】:

    在开发环境localhost;任何使用 UI 框架的客户端应用程序都需要调整服务器会话 cookie 代码,如下所示。

    注意:在您的后端服务器上,您需要将httpOnly 的 cookie 设置转换为 False,如下代码所示

    cookie: {
           secure: false, //set this to true in production over https
           httpOnly: false, //set this to false in development to test delete 
           ....
           ....
    }
    

    稍后,在您的 Angular 服务代码中使用如下注销方法:

    logout(){
    
    this.cookieService.delete('<your-cookie-name>', '/', 'localhost', false, 'Lax');
    
    }
    

    See ngx-cookie-service documentation

    个人删除:

    delete( name: string, path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax'): void;
    

    批量删除:

    deleteAll( path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax' ): void;
    

    重要提示:在生产中,两者都应设置为 True | httpOnly & Secure | Cookie

    【讨论】:

      【解决方案3】:

      我假设你使用 ngx-cookie-service?

      请检查您的代码的执行顺序并将路径设置为'/'

      我一直在摆弄它,似乎设置一个同名的 cookie 会覆盖现有的。因此,如果订单不正确,您将不会看到您的 cookie 被删除。

      我没有时间检查你提到的路径部分。我没有实现带有路径的路由器,看看是否可以帮助您。

      通过以下方式设置 cookie: Service.setcookie('name', 'value', int, '/'); 应该可以正常工作

      并删除它: CookieService.deleteAll() 也适用于 ngOnInit()

      我很确定它的执行顺序并提供路径为 '/' 。

      这样就好了。

      抱歉,没有漂亮的代码,我在手机 atm 上,如果仍然需要,稍后会更新。我不得不离开我的电脑。

      【讨论】:

        猜你喜欢
        • 2014-11-20
        • 2014-05-19
        • 2019-10-23
        • 1970-01-01
        • 2013-01-02
        • 2010-09-15
        相关资源
        最近更新 更多