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

Nx Angular使用PathLocationStrategy刷新后出现404问题求助

Nx Monorepo中Angular路由PathLocationStrategy本地404问题解决

问题场景

在Nx monorepo的Angular沙箱应用中配置路由时,设置useHash: true(哈希策略)一切正常:

  • 访问/自动重定向到/welcome
  • 刷新或直接访问/welcome页面正常加载
  • 非法路径自动重定向到/welcome

但切换为useHash: false(PathLocationStrategy)后,仅根路径/可正常访问,刷新或直接访问其他路径均返回404错误。当前路由及相关配置如下:

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    NxWelcomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    {provide: LocationStrategy, useClass: PathLocationStrategy}
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

app-routing.module.ts

const routes: Routes = [
  {
    path       : 'welcome',
    component  : NxWelcomeComponent
  },
  {path: '', redirectTo: 'welcome', pathMatch: 'full'},
  {path: '**', redirectTo: 'welcome'}
];

const routeConfig: ExtraOptions = {
  scrollPositionRestoration: 'top',
  useHash: false,
}

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

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Sandbox</title>
    <base href="/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
  </head>
  <body>
    <app-root></app-root>
  </body>
</html>

app.component.html

<router-outlet></router-outlet>

问题原因

Angular的PathLocationStrategy依赖服务器将所有路由路径重定向到index.html,由Angular自身接管路由匹配。Nx默认的本地开发服务器未配置该 fallback 规则,因此刷新或直接访问子路径时,服务器会尝试寻找对应物理文件,找不到则返回404。

解决方案

方案1:直接修改Nx项目服务配置

在项目根目录的project.json中,找到targets.serve.options,添加historyApiFallback: true:

"serve": {
  "executor": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "sandbox:build",
    "historyApiFallback": true
  },
  "configurations": {
    "production": {
      "browserTarget": "sandbox:build:production"
    }
  }
}

该配置会让webpack-dev-server将所有404请求重定向到index.html,Angular路由即可正常处理。

方案2:使用代理配置文件(适用于需额外代理API的场景)

创建proxy.conf.json文件(路径示例:apps/sandbox/proxy.conf.json):

{
  "historyApiFallback": {
    "index": "/index.html"
  }
}

然后在project.json的serve.options中引入该配置:

"serve": {
  "executor": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "sandbox:build",
    "proxyConfig": "apps/sandbox/proxy.conf.json"
  },
  ...
}

临时替代方案(环境区分策略)

若暂时不想修改服务器配置,可保留本地用哈希策略、生产环境用路径策略的配置:

const routeConfig: ExtraOptions = {
  scrollPositionRestoration: 'top',
  useHash: !environment.production,
}

验证

修改配置后重启Nx本地服务(执行nx serve sandbox),刷新或直接访问/welcome等子路径即可正常加载页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:15:43