URL在Tomcat 8服务器上重写Angular 4 [英] Url rewriting Angular 4 on tomcat 8 server

查看:121
本文介绍了URL在Tomcat 8服务器上重写Angular 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have deployed an angular 4 application (with angular routing) on tomcat server with "frontend-maven-plugin" (V1.6) but url comportement is very strange.

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

In fact, when i click on refresh button on all pages, there is a HTTP 404 error. When i try to acess on root page, there is no redirection to index.html.

这些错误仅在tomcat部署中出现(在nodejs上正常工作).

Theses error are only present with tomcat deployment (it work fine with nodejs).

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

How can i configure tomcat in order to correct this problems ?

感谢您的回复.

推荐答案

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

I think you are getting 404 because your are requesting http://localhost/route which doesn't exist on tomcat server. As Angular 2 uses html 5 routing by default rather than using hashes at the end of the URL, refreshing the page looks like a request for a different resource.

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

When using angular routing on tomcat you need to make sure that your server will map all routes in your app to your main index.html while refreshing the page. There are multiple way to resolve this issue. Whichever one suits you you can go for that.

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

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

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

尝试使用:

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

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

代替:

RouterModule.forRoot(路由)

RouterModule.forRoot(routes)

使用HashLocationStrategy,您的网址将像:

With HashLocationStrategy your urls gonna be like:

http://localhost/#/route

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

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

3.1) Inside META-INF folder create a file context.xml and copy the below context inside it.

    <? 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中,复制以下内容:

3.2) Inside WEB-INF, create file rewrite.config(this file contain the rule for URL Rewriting and used by tomcat for URL rewriting). Inside rewrite.config, copy the below content:

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

这篇关于URL在Tomcat 8服务器上重写Angular 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆