链接到错误的最小再现(stackBlitz):
https://stackblitz.com/edit/angular-viq7wd?file=src%2Fapp%2Fauth.service.ts 如果要重现该错误,则需要在本地运行该代码。
我使用 Angular 12 库和“ngx-cookie-service”:“13.1.2”。我试图为域(localhost)及其子域(sub1.localhost、sub2.localhost)添加一个cookie(包含用户数据)。
Angular 应用程序使用 AuthService 并在 localhost 上运行。它设置了一个cookie:
setUserData(userData: string) {
this.cookieService.set(this.COOKIE_NAME, JSON.stringify(userData) , 36000000, '/', this.DOMAIN);
}
但是在sub1.localhost上运行的应用程序无法检索 cookie 数据(为localhost设置的):
getUserData(): string {
let userData = this.cookieService.get(this.COOKIE_NAME);
return userData;
}
这是身份验证服务:
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
@Injectable({ providedIn: 'root' })
export class AuthService {
private DOMAIN: string = 'localhost';
private COOKIE_NAME: string = 'NGX-COOKIE-NAME';
constructor(private cookieService: CookieService) { }
getUserData(): string {
let userData = this.cookieService.get(this.COOKIE_NAME);
return userData;
}
setUserData(userData: string) {
this.cookieService.set(this.COOKIE_NAME, JSON.stringify(userData)
, 36000000, '/', this.DOMAIN
);
}
clearUserData() {
let c = this.cookieService.get(this.COOKIE_NAME);
if (c != null)
this.cookieService.delete(this.COOKIE_NAME
, '/', this.DOMAIN
);
}
}
我使用命令运行应用程序(它作为“s”添加到 package.json 脚本中 - 您可以通过“npm run s”运行它):
"ng serve --host localhost --disable-host-check --port 4200 --open"
另外,是否可以从 localhost 域的 sub1.localhost 设置 cookie?
重现步骤:
- 从 Stackblitz 下载代码:https ://stackblitz.com/edit/angular-viq7wd?file=src%2Fapp%2Fauth.service.ts
- 使用“ npm run s ”命令运行代码(该命令已添加到 package.json 文件中)。之后,应用程序应该在localhost:4200上运行。
- 使用标有“cookie 值”的输入元素提供任何值,然后按“保存 cookie 按钮”。之后,应该为localhost域设置一个新的 cookie。
- 在地址栏中将 url 从“localhost:4200”更改为“sub1.localhost:4200”。之后,应用程序应该重新启动。
- 单击“读取 cookie”按钮以检索步骤3中设置的 cookie 数据。问题:cookie数据无法检索;localhost 域 cookie 对于 sub1.localhost 域不可见。