【问题标题】:Angular 4 Router - Page Not Found Error on RedirectAngular 4路由器-重定向时找不到页面错误
【发布时间】:2017-09-12 15:19:18
【问题描述】:

我有一个运行良好的 Angular 4 应用程序。

我一直在使用 HashLocationStrategy,但我决定不再在我的网址中使用哈希。

我的路由器设置现在看起来像这样......

export const routes: Routes = [
  {
    path: '',
    component: TilesComponent
  },
  {
    path: 'profile/:urlUserName',
    component: ProfileComponent
  },
  {
    path: 'forBusiness',
    component: ForBusinessComponent
  },
  {
    path: 'login',
    component: LoginPageComponent
  },
  {
    path: 'editTile/:urlUserName',
    component: EditTileComponent,
    canActivate: [AuthenticationService]
  }

];

export const appRoutingProviders: any[] = [];

export const routing = RouterModule.forRoot(routes, { });

我有一个来自我的打开页面的链接,它是这样生成的...

routerLink="/forBusiness"

它重定向到这个页面...

https://www.tilecase.com/forBusiness

现在,如果我将此 URL 放入浏览器并尝试单独加载 forBusiness 页面,我会收到“找不到页面”错误。

我需要对我的路线或页面设置做些什么才能使其正常工作?

【问题讨论】:

  • 当您切换到不同的 LocationStrategy 时,无需更改 Angular 代码中的任何内容。但是,您的服务器需要支持 HTML5 pushState,并且需要进行配置。
  • 一如既往的感谢。我正在使用 Netlify 进行 seo 渲染。我不确定他们是否提供。还有其他方法可以删除哈希吗?
  • 不,如果服务器不支持 HTML5 pushState,那么就没有办法 AFAIK。

标签: angular angular4-router


【解决方案1】:

LocationStrategy 有两种类型 1. HashLocationStrategy 2.路径定位策略

你需要PathLocationStrategy

将此添加到您的root-module

import {LocationStrategy, PathLocationStrategy} from '@angular/common'

 // add this in provider
{ provide: LocationStrategy, useClass: PathLocationStrategy }

如果您的服务器是 apache,只需创建一个名称为 .htaccess 的文件即可粘贴此数据

 <IfModule mod_rewrite.c>
     Options Indexes FollowSymLinks
     RewriteEngine On
     RewriteBase /myappdirectory/
     RewriteRule ^index\.html$ - [L]
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule . /index.html [L]  <--- get the index.html file path starting from public html folder
 </IfModule>

根据命令更新最后一行

保存然后刷新您的页面。幸运的是您的页面可以正常工作

对于 IIS 服务器,请点击此链接

http://jasonwatmore.com/post/2017/02/24/angular-2-refresh-without-404-in-node-iis

【讨论】:

  • 太好了,谢谢。我会试一试。您知道这是否适用于 netify.com 上托管的网站吗?
  • 删除{useHash: true} 与提供PathLocationStrategy 的作用相同。 PathLocationStrategy 是默认值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 2022-11-09
  • 2019-06-03
  • 2016-07-07
相关资源
最近更新 更多