URL在Tomcat 8服务器上重写Angular 4

Jér*_*émy 2 tomcat url-rewriting url-routing maven angular

我已经在带有“ frontend-maven-plugin”(V1.6)的tomcat服务器上部署了一个angular 4应用程序(带有角度路由),但是url组合非常奇怪。

实际上,当我单击所有页面上的刷新按钮时,就会出现HTTP 404错误。当我尝试在根页面访问时,没有重定向到index.html

这些错误仅在tomcat部署中出现(与nodejs配合正常)。

我如何配置tomcat来纠正此问题?

感谢您的回复。

小智 9

我认为您正在获取404,因为您正在请求http:// localhost / route,而该服务器在tomcat服务器上不存在。由于Angular 2默认使用html 5路由,而不是在URL末尾使用哈希,因此刷新页面看起来就像是对其他资源的请求。

在tomcat上使用角度路由时,您需要确保服务器在刷新页面时将应用程序中的所有路由映射到主index.html。有多种方法可以解决此问题。无论哪种适合您,您都可以这样做。

1)将以下代码放在部署文件夹的web.xml中:

<error-page>
     <error-code>404</error-code>
     <location>/index.html</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

2)您也可以尝试将HashLocationStrategy与路由的URL中的#一起使用

尝试使用:

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

代替:

RouterModule.forRoot(routes)

使用HashLocationStrategy,您的网址将类似于:

http:// localhost /#/ route

3)Tomcat URL重写阀:如果找不到资源,则使用服务器级别的配置来重写URL,以重定向到index.html。

3.1)在META-INF文件夹中,创建一个文件context.xml,并在其中复制以下上下文。

    <? xml version='1.0' encoding='utf-8'?>
    <Context>
      <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
    </Context>
Run Code Online (Sandbox Code Playgroud)

3.2)在WEB-INF内,创建文件rewrite.config(此文件包含URL重写规则,tomcat用于URL重写)。在rewrite.config中,复制以下内容:

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