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

Angular项目新标签页打开页面报404,本地正常部署后异常求助

问题:Angular部署后新标签页打开路由报错,本地正常

尝试在新标签页打开页面,本地环境运行正常,但部署到服务器后出现如下错误:

Oops, looks like the page is lost.
This is not a fault, just an accident that was not intentional.

相关代码

路由配置

const routes: Routes = [
  { path: ' ', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'resource', component: ResourceDetailsComponent },
  { path: 'careers', component: CareerComponent }
];

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

组件代码

<a class="view" (click)="redirect(a)"
            >VIEW MORE VACANCIES</a
          >
redirect(){
    localStorage.removeItem("selectedCareer");
    window.open("/careers", '_blank');
}

问题原因与解决方法

  1. 修复路由配置的空格问题
    路由里默认重定向的路径存在多余空格:{ path: ' ', redirectTo: 'home', pathMatch: 'full' },把' '改成空字符串'',确保根路径能正确匹配重定向规则。

  2. 配置服务器路由转发
    Angular是单页应用,本地开发服务器会自动把所有路由请求导向index.html,但部署到外部服务器后,直接访问/careers这类路由时,服务器会去寻找对应的物理文件,找不到就返回404。需要给服务器添加规则,让所有请求都转发到index.html:

    • Nginx:在配置文件的location /块中添加
      try_files $uri $uri/ /index.html;
      
    • Apache:创建.htaccess文件,写入
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.html [L]
      
    • 其他服务器(如IIS、Node.js)也需要类似配置,确保所有路由请求都由Angular路由器处理。
  3. 用Angular Router生成正确URL
    直接用window.open("/careers")可能在部署到子目录时出现路径错误,建议通过Angular Router生成完整URL:

    import { Router } from '@angular/router';
    
    constructor(private router: Router) {}
    
    redirect() {
        localStorage.removeItem("selectedCareer");
        const fullUrl = this.router.serializeUrl(this.router.createUrlTree(['/careers']));
        window.open(fullUrl, '_blank');
    }
    

    这种方式会自动带上应用的基础路径,避免部署环境的路径问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:06:24