【问题标题】:Deploy Angular2 App to Tomcat8 - Routing does not seems to work将 Angular2 应用程序部署到 Tomcat8 - 路由似乎不起作用
【发布时间】:2019-04-10 20:28:09
【问题描述】:

我在尝试将 Angular2 应用程序部署到 tomcat8 时遇到了一个奇怪的问题。

首先是上下文: - 我使用 Angular Cli 来协助我的构建过程。 - 应用程序在服务器本地完美运行:ng serve - ng build 使我的 dist/ 目录包含所有产品资源 - 我创建了一个 gulp 任务来创建一个 WAR,以便将应用程序正确部署到 Tomcat。 - 战争部署到tomcat webapps 目录

我的应用 URI 是这样的:https:\www.myexample.com\myapp\

主页 uri 运行良好; 当尝试使用 Angular2 路由时,问题就开始了;例如 https:\www.myexample.com\myapp\myroute.

Tomcats 认为它​​是一个新的 webapp 目录,不做任何转发 https:\www.myexample.com\myapp\index.html

我看过几篇关于这种行为的帖子,但到目前为止;我还没有看到任何解决方案。

有没有人知道如何克服这个问题以在 tomcat8 上正确运行我的 angular2 应用程序?

感谢支持。

【问题讨论】:

  • 尝试添加RouterModule.foRoot(useHash: true)。如果它以这种方式工作,那么您的服务器需要配置为支持 HTML5 pushState。
  • 请将此添加为答案,因为它可以节省我的时间@GünterZöchbauer
  • 如果 shussons 的回答有帮助,请随时接受他的回答。

标签: angular tomcat8 angular-cli


【解决方案1】:

除非目录或文件存在,否则您需要重写 URL 以提供 index.html

配置Tomcat使用重写阀https://tomcat.apache.org/tomcat-8.0-doc/rewrite.html

然后将如下内容添加到rewrite.config 文件中:

# If dir or asset exists go to it
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# Rewrite all other urls to use index.html
RewriteRule ^ /index.html

【讨论】:

  • 我应该把rewrite.config放在哪里?
  • 有没有办法在 Java 控制器中做这个服务器端?我想我有一个类似的问题,我的应用程序从 ng serve 运行良好,但是当我将它捆绑在战争中时,如果它涉及 /home 或 /inbox 等路由,浏览器刷新将停止工作。如果涉及路由,我会在浏览器刷新时收到 404。如果我在应用程序中单击,路由工作正常。谢谢
【解决方案2】:

添加RouterModule.forRoot(useHash: true) 切换到使用# 的URL,它适用于每个服务器。

要使用 HTML5 pushState(Angular 默认),您的服务器需要配置为支持它。

两种风格的比较见https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles

【讨论】:

    【解决方案3】:

    Angular (2+) 支持两种类型的路由策略——HashLocationStrategyPathLocationStrategyPathLocationStrategy 是使用 Angular CLI 构建应用程序时的默认配置。 PathLocationStrategyHashLocationStrategy 有很多优势,并且是文档 here 中讨论的推荐配置。

    PathLocationStrategy 的缺点是需要在服务器端进行特定的配置。如果服务器端不做这个配置,那么直接访问深度链接时会导致404。此配置还取决于正在使用的服务器。

    用于解决在 apache tomcat 服务器 (8, 9) 上部署 Angular 应用程序(使用 PathLocationStrategy 路由)时的深层链接问题 -

    1. 在 server.xml 中配置 RewriteValve
    2. 在rewrite.config中写入重写规则

    server.xml -

    ...
          <Host name="localhost"  appBase="webapps"
                unpackWARs="true" autoDeploy="true">
    
            <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
    
    ...
          </Host>
    ...
    

    rewrite.config - (注意 - /hello/ 是 Angular 应用在​​ tomcat 上的上下文路径)

    RewriteCond %{REQUEST_PATH} !-f
    RewriteRule ^/hello/(.*) /hello/index.html
    

    我在我的文章中记录了这个问题 - Fixing deep linking issue – Deploying angular application on Tomcat server

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 2012-12-12
      • 2017-07-24
      • 2021-11-18
      • 2021-10-31
      相关资源
      最近更新 更多