首页 文章

Angular 2路由无法使用Apache进行页面刷新

提问于
浏览
2

使用Angular 2 RC 4和更新的@ angular / router,我使用this question中的答案获得了在浏览器中显示的路径URL

但是,当我刷新或直接请求具有非默认路由的页面时,它会将我带到默认页面(就像我请求index.html)而不是我想要的路由页面 . 如何使用Apache 2.4在页面刷新时使Angular 2路由正常工作?

路线和引导:

const routes: RouterConfig = [
{ path: '', redirectTo: 'dashboardTab', terminal: true },
{ path: 'dashboardTab', component: DashboardComponent },
{ path: 'missionTab', component: MissionComponent, children: childRoutes }];

bootstrap(NavbarComponent, [disableDeprecatedForms(), provideForms(),   provideRouter(routes), {provide: Window, useValue: window}, HTTP_PROVIDERS, ResponsiveState, {provide: PLATFORM_DIRECTIVES, useValue: RESPONSIVE_DIRECTIVES, multi: true}]).catch((err: any) => console.error(err));

index.html中的基数href: <base href="/">

2 回答

  • 0

    使用apache2的vhost中的代码:

    <Directory /var/www/html/yourproject>
        Options Indexes FollowSymLinks
        RewriteEngine On
        RewriteBase /yourproject
        RewriteRule ^index\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /yourproject/index.html [L]
    </Directory>
    

    并使用index.html中的代码

    <script>document.write('<base href="' + document.location + '" />');</script>
    

    这解决了 .

  • 0

    基本上apache对你的角度应用路线一无所知,所以它在这里做不了多少 .

    But

    这里的诀窍是让你的apache服务器提供 index.html 文件,即使在找不到页面的情况下,这样角度就可以呈现路线 .

    Here are the steps

    • 在angular applicaiton src 文件夹中创建名为 .htaccess 的文件,并将以下代码复制到其中
    RewriteEngine On
          RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
          RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
          RewriteRule ^ - [L]
      RewriteRule ^ /index.html
    
    • 您需要将此 .htaccess 文件添加到 angular.json 中的 assets 数组中,以便在执行 生产环境 构建时,angular会将其复制到 dist 文件夹 .

    • 最后在创建 生产环境 版本后,如果将应用程序复制到apache服务器,一切都应该可以正常工作,但如果没有,你可能想做最后一步

    转到服务器内的 /etc/apache2/apache2.conf 并进行修改

    <Directory /var/www/>
            Options Indexes FollowSymLinks
            AllowOverride None
            Require all granted
    </Directory>
    

    看起来像这样

    <Directory /var/www/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
    </Directory>
    

    如果这不起作用,可能你可能没有启用mod重写

    sudo a2enmod rewrite
    

    请参阅angular团队的部署指南

    https://angular.io/guide/deployment

相关问题