【问题标题】:How to route in angular 4如何在角度 4 中路由
【发布时间】:2017-12-02 19:27:59
【问题描述】:

我有一个 angular 4 项目,当我从 localhost:4200/route-a 运行它时,它运行良好,当我刷新浏览器时,一切正常。但是,当我使用 ng build 构建它并从 apache 运行它时,导航到 localhost/route-a 会返回一个 404。这是我的路由代码:

imports: [BrowserModule, HttpModule, FormsModule, RouterModule.forRoot([
    { path: 'home', component: HomeComponent },
    { path: 'route-a', component: RouteAComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
  ])]

【问题讨论】:

  • 你必须configure your apache server 允许html5routing
  • 因为它不是像服务器那样的路由:它是加载 html 模板的路由。如果你想让它工作,你必须将你的服务器设置为重定向到你所做的每条路由。
  • 谢谢大家让我试试

标签: angular apache angular4-router


【解决方案1】:

这不是 Angular 问题。这是您的 apache 设置的问题。 当您在 Angular 中使用 HTML5 模式(漂亮的 url)时,您必须配置 Apache 以将服务器上不存在资源的所有请求发送到 index.html 文件。

这可以通过以下 .htaccess 配置来完成:

RewriteEngine On  
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

原因是当你尝试访问/route-a时,apache服务器会默认尝试查找目录route-a和其中的index.html文件。但是因为你没有那个目录,apache会不会返回404错误。

但是通过告诉 apache,在任何位置或文件不存在的请求中。要发送发送您的 Angular html 文件,Angular 路由器会从那里接收它吗?

【讨论】:

    【解决方案2】:

    从 Apache 版本 2.2.16 开始,您可以为此使用 FallbackResource 指令:

    <Directory "/var/www/my_blog">
      FallbackResource index.php
    </Directory>
    

    查看https://httpd.apache.org/docs/trunk/rewrite/remapping.html#fallback-resource

    【讨论】:

      【解决方案3】:

      有时您可能无权访问服务器配置。 对此还有另一种可能的解决方案。

      RouterModuleimport 中有类似的内容:

      RouterModule.forRoot( routes )
      

      您可以这样添加useHash

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

      然后使用生产标志重建您的项目,现在的 URL 将如下所示:

      http://yourserver/#/page1/
      

      这样,由于散列,应用程序将毫无问题地运行,唯一需要的是在 RouterModule 上设置 useHash 并重建您的应用程序。

      重写规则很好,但我认为有更多选择很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多