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

Angular路由跳转异常:点击按钮出现Cannot POST错误求助

解决Angular路由跳转出现POST 404的问题

问题原因

你的按钮设置了type="submit",如果该按钮包裹在<form>标签内,点击时会优先触发表单的默认POST提交行为,这会覆盖Angular的客户端路由跳转逻辑,导致浏览器向服务器发送POST请求到/newcomponent,而服务器没有对应的POST接口,因此返回404错误。

解决方案

方案1:修改按钮类型为button

将按钮的type="submit"改为type="button",彻底避免触发表单提交:

<button type="button" (click)="goToComponent()">Login</button>

方案2:阻止表单默认提交行为(需保留submit类型时)

如果必须使用type="submit",可以在点击事件中阻止默认行为:

  • 模板中直接处理:
<button type="submit" (click)="goToComponent(); $event.preventDefault()">Login</button>
  • 或在组件方法中处理:
    组件代码:
goToComponent(event: Event){
  event.preventDefault();
  this.router.navigate(['/newcomponent']);
}

模板代码:

<button type="submit" (click)="goToComponent($event)">Login</button>

额外优化建议

当前路由配置中把AppComponent作为login路径的组件不太合理,通常AppComponent是项目根组件,应该在其模板中添加<router-outlet></router-outlet>,然后单独创建LoginComponent作为登录页面组件,这样路由跳转后的内容才能正确渲染到路由出口中:

修改路由配置:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login.component'; // 导入专门的登录组件
import { NewComponent } from './new.component';

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'newcomponent', component: NewComponent}
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

在app.component.html中添加路由出口:

<router-outlet></router-outlet>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:40:42