You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material应用Safari登录后账号密码追加至URL问题求助

解决Safari中登录后URL追加用户名和密码的问题

嘿,我来帮你搞定这个困扰!你遇到的问题是因为Safari和Chrome对表单默认提交行为的处理差异导致的,咱们一步步来解决:

问题根源

你的表单没有明确指定提交方式,默认会使用GET方法提交——这就会把表单里的userId和password拼到URL里。虽然你同时给表单绑了ngSubmit、给按钮绑了click事件,但Safari的浏览器行为没有阻止表单的默认提交动作,而Chrome在这类场景下自动拦截了,所以出现了差异。另外,按钮同时绑定click和表单的ngSubmit也可能导致事件触发冲突,加重这个问题。

解决方案

我推荐你按照Angular表单的最佳实践来修改,既简单又能彻底解决问题:

1. 修改登录页模板

把按钮的click绑定移除,改用表单的ngSubmit统一处理登录逻辑,同时给表单明确加上method="post",并确保按钮是submit类型:

<form (ngSubmit)="doLogin()" method="post">
  <div>
    <input matInput placeholder=" User ID" name="userId" [(ngModel)]="userId">
  </div>
  <div>
    <input matInput type="password" name="password" placeholder=" Password" [(ngModel)]="password">
  </div>
  <div>
    <button mat-raised-button type="submit">Sign In</button>
  </div>
</form>

2. 为什么这样改?

  • ngSubmit是Angular专门为表单设计的提交事件,它会自动调用preventDefault()阻止浏览器的默认表单提交行为,从根源避免GET提交带参数的问题。
  • 加上method="post"是双重保险,明确告诉浏览器不要用GET方式提交表单。
  • 移除按钮的click绑定,避免和ngSubmit触发重复的登录逻辑,同时消除事件冲突的可能。

备选方案(应急用)

如果你暂时不想改模板,也可以在doLogin方法里手动阻止默认事件:

userId: string;
password: string;

doLogin(event?: Event) {
  if (event) {
    event.preventDefault(); // 阻止浏览器默认提交行为
  }
  this.errorMessage = '';
  if (this.userId == undefined || this.userId == '') {
    this.errorMessage = 'Authentication Failed';
    return;
  }
  var user: UserModel = this.dataStore.findUser(this.userId.trim().toLowerCase());
  if (user == undefined || (user.password != this.password)) {
    this.errorMessage = 'Authentication Failed';
    return;
  }
  this.core.currentUser = user.userId;
  this.router.navigate(['homepage']);
}

然后把按钮改成:

<button mat-raised-button (click)="doLogin($event)">Sign In</button>

不过还是首选第一种方案,更符合Angular的设计规范,代码也更整洁。

验证修改

改完之后,在Safari里测试登录,URL就不会再带着userid和password参数了,和Chrome的表现一致。

内容的提问来源于stack exchange,提问作者Vik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:32:32