刷新浏览器 Angular 应用程序不工作。当我将应用程序部署到 apache tomcat 时出现 404 错误

Refresh The browser Angular app is not working. giving 404 error when I deployed the app in to apache tomcat

我正在尝试了解如何设置 Apache Tomcat 服务器以在页面刷新时为 angular 应用程序提供服务。

路由仅在我单击时有效,但如果手动输入路径或如果我刷新页面,则会出现 404 错误。

HTTP Status 404 – Not Found

1) 构建 angular 应用程序:

ng build --prod --base-href ./

2) 我还在 apache 中添加了重写规则 tomcat

在$ApacheLocation/conf/context.xml

<Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />

在$ApacheLocation/conf/server.xml

<Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />

但它对我不起作用。

如有任何帮助,我将不胜感激。

我不是 Apache 专家,但这是我的发现。 将重写规则添加到 .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

您可以在 https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/ 要么 https://angular.io/guide/deployment#fallback-configuration-examples

我也遇到了同样的问题。让我说说我是如何解决这个问题的。

在您的项目文件夹中创建 WEB-INF 文件夹。并创建 rewrite.config 文件。

/WEB-INF/rewrite.config

RewriteCond %{SERVLET_PATH} !-f
RewriteRule ^/(.*)$ /index.html [L]

我得到了我的问题的解决方案并且我解决了问题。

这是我如何解决问题的步骤。

1)在我的angularsrc文件夹中创建"WEB-INF/web.xml",路径如下

Your_Folder/src/WEB-INF/web.xml

2) 在 web.xml 中我添加了以下行,

<web-app> 
    <error-page> 
        <error-code>404</error-code> 
        <location>/index.html</location> 
    </error-page> 
</web-app>

3) 将外部文件夹添加到 angular.json 以便在构建应用程序时可以在 dist 文件夹中使用它,

在angular.json

"assets": [ "src/assets","src/favicon.ico","src/WEB-INF" ]

4) 使用以下命令构建应用程序,

ng build --prod --base-href=/myApp/

5) 将 dist 文件夹重命名为 base-href 名称

6) 复制 distbase-href 文件夹并粘贴到

apache-tomcat-8.5.37/webapps

7) 启动 tomcat,您的应用程序将 运行,即使在刷新浏览器后也是如此。

您可以在 app.module.ts

中使用如下所示的 HashLocationStrategy
providers: [
    { provide: LocationStrategy, useClass: HashLocationStrategy }
  ],

通过使用散列定位策略,您的应用程序上下文和路由将由散列 (#) 分隔,如 http://localhost:4200/myapp/#/route

这样404错误就解决了。我们也有 PathLocationStrategy,但我无法让它工作。

您刚刚在 server.xml 中配置了 RewriteValve。除此之外,您还需要在 rewrite.config.

中编写重写规则

rewrite.config -

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

以上规则告诉 tomcat 将任何请求(深度链接请求)重定向到应用程序的 index.html。从这里 angular 将接管并路由到要显示的正确组件。

我建议将应用程序托管在 tomcat 上的单独上下文路径中,而不是在根目录中。此博客上详细解释了为此所需的配置 - Fixing deep linking issue – Deploying angular application on Tomcat server