首页 文章

Url在tomcat 8服务器上重写Angular 4

提问于
浏览
0

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

实际上, when i click on refresh button on all pages, there is a HTTP 404 error . 当我尝试 acess on root page, there is no redirection to index.html .

这些错误是 only present with tomcat deployment (它与nodejs一起使用) .

我如何配置tomcat以纠正这个问题?

谢谢你的回复 .

1 回答

  • 2

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

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

    1) Put below code in web.xml of your deployment folder :

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

    2) You can also try using HashLocationStrategy with # in the URL for routes

    尝试使用:

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

    代替:

    RouterModule.forRoot(路由)

    使用HashLocationStrategy你的网址将是:

    http://localhost/#/route

    3) Tomcat URL Rewrite Valve : Re-write the url's using a server level configuration to redirect to index.html if the resource is not found.

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

    <? xml version='1.0' encoding='utf-8'?>
        <Context>
          <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
        </Context>
    

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

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

相关问题