首页 > 解决方案 > 无法使用 ngx-cookie-service 设置 cookie

问题描述

我正在使用angular 9,我需要设置一个 cookie。我正在使用ngx-cookie-service 3.0.4,我正在尝试这样做:

this.cookieService.set("cookieName", user.tokenId, date, "/", "localhost:4200");

当我试图摆脱这个时,我在响应中得到 null,在浏览器中我没有看到这个 cookie。我试图得到如下结果:

console.log("COOKIE: ", this.cookieService.get("cookieName));

我做错了什么?

标签: javascriptangulartypescriptngx-cookie-service

解决方案


为 localhost 设置 cookie 时,不能'localhost:4200'用作域。这是设计使然,您可以在此处阅读更多相关信息:具有显式域的 localhost 上的 Cookie

在这种情况下,当应用程序在 localhost 上运行时,您可以完全传入null或省略域。

const hostName = isLocal ? null : 'HOST_NAME';
this.cookieService.set("cookieName", user.tokenId, date, "/", hostName);

推荐阅读