【问题标题】:Angular Router Get 404 Bug?Angular 路由器得到 404 错误?
【发布时间】:2018-02-02 08:57:27
【问题描述】:

我的问题是每次我加载我的链接。前任: "https://www.example.com/" 它将重定向到 “https://www.example.com/design-brief”,因为我在 routing.ts 中配置了它。 但是当我使用链接“https://www.example.com/design-brief”并在我的地址栏中输入时,它会在控制台日志中显示错误。 "GEThttps://www.example.com/design-brief404()"

const APP_ROUTES: Routes = [
{ path: 'design-brief', component: DesignBriefComponent },
{ path: 'design-evaluation', component: DesignEvaluationComponent },
{ path: '', redirectTo: '/design-brief', pathMatch: 'full' },
{ path: "**",redirectTo:"/design-brief" } ];

这是我在 routing.ts 中的代码

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    你不需要空路径和**路径,只需要pathMatch 'full'的**路径:

    const APP_ROUTES: Routes = [
    { path: 'design-brief', component: DesignBriefComponent },
    { path: 'design-evaluation', component: DesignEvaluationComponent },
    { path: "**",redirectTo:"design-brief",pathMatch: 'full' } ];
    

    并且重定向不需要设计简介前面的斜杠(/)

    【讨论】:

    • 但如果我删除它,页面将不会重定向到“设计简介”页面。我正在使用 angular-cli-ghpages。当我使用链接“example.com/design-brief”时,它仍然在我的控制台日志中显示“GET example.com/design-brief404()”
    【解决方案2】:

    请参阅my answer here,了解有关发生这种情况的原因的更详细说明。

    简而言之,您有两种选择:

    1. 将您的 Web 服务器配置为始终使用 index.html 每当检测到 404 时——这样,Angular 总是 load 及其路由服务将处理 客户端。

    2. 将应用的 locationStrategy 更改为 Hash 位置策略 描述here。但是,这会改变您应用的 URL,而且 在我看来不是那么理想。

    【讨论】:

    • 它解决了我的问题。谢谢。顺便说一句,有没有办法删除“#”?我的意思是,有没有办法在不使用哈希的情况下修复它?
    • 干净的方法是使用默认的位置策略(而不是哈希),并在 Web 服务器上进行一些配置,正如我所提到的。如果您确实使用了 HashLocationStrategy,那么 # 将保留 :)
    • 如何配置?我只是在使用 github (angular-cli-ghpages),这样我就可以看到我的 angular-app 正在运行。这只是为了我的练习。但我想学习干净的方式或正确的方式。
    • 对于 github 这有点棘手,因为我认为你没有办法为底层托管 Web 服务器提供一些配置(也许你有,我不确定)。我发现@RahulSingh 的其他解决方法,查看他的帖子here(第15 点)
    • 但总的来说,作为一个例子,要为 IIS 检查我的其他答案 here 和 apache here
    【解决方案3】:

    我通过使用哈希定位策略解决了这个问题。将以下代码添加到 @ngModule 的导入部分,并在所有超链接前面加上 # 并参考官方link 了解信息

    RouterModule.forRoot(
       appRoutes,{ useHash: true }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 2020-10-07
      • 2017-08-31
      • 2015-02-04
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多