小编典典

在Apache Tomcat 404深度链接上部署角度应用程序

tomcat

我试图弄清楚如何设置Apache Tomcat服务器以为具有深层链接的角度应用程序提供服务。例如:

静态服务器在收到对mysite.com/的请求时,通常会返回index.html。但是它拒绝mysite.com/heroes/42并返回404-Not
Found错误,除非将其配置为返回index.html。

我想在localhost / angular上提供angular应用,我尝试了以下方法:

1)用以下方法构建角度应用程序:

ng build --prod --base-href .

2)将构建文件夹的内容(默认:dist)复制到$ ApacheLocation / webapps / angular

3)在$ ApacheLocation / conf / Catalina / localhost /
rewrite.config中添加RewriteRules

# 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 ^\/angular\/.*$ /angular/index.html

4)在主机标签正下方添加阀门

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

5)启动Tomcat服务器并转到localhost / angular将给我:

未捕获到的SyntaxError: 所有.js软件包(例如main.bundle.js)的 意外令牌 <

如果我不包括重写规则,tomcat将按预期提供localhost / angular的服务, 但会在深度链接上提供404。

我的设置配置:

  • tomcat version 9.0.0.M26
  • angular version 4.4.2
  • @angular/cli: 1.4.2
  • node: 8.5.0
  • npm:5.4.2
  • os: linux x64

阅读 269

收藏
2020-06-16

共1个答案

小编典典

我设法通过以下步骤解决了此问题,例如http:// localhost:8080 / angular / player / detail /
4

1)使用以下命令构建角度应用程序:ng build –prod -bh ./ -d / angular

2)将已构建应用的内容复制到$ ApacheLocation / webapps / angular

3)重写规则:

RewriteCond %{REQUEST_PATH} !-f
RewriteRule ^/angular/(.*) /angular?path=$1

4)在app.component.ts上的设置导航:

constructor(private activatedRoute: ActivatedRoute, private router: Router) { }

ngOnInit() {
const path = this.activatedRoute.snapshot.queryParams['path'];
const navigateTo = '/' + path;

if (path) {
  this.router.navigate([navigateTo]);
}

}

您可以在这里找到测试项目:https :
//github.com/avuletica/test

重写规则说明:

# %{REQUEST_PATH} corresponds to the full path that is used for mapping.
# ! NOT character 
# '-f' (is regular file) Treats the TestString as a pathname and tests whether or not it exists, and is a regular file.
# ^ matches the beginning of the string or line
# . matches any charceter except line breaks
# * match 0 or more of the preceding token

因此,基本上,如果在/ angular/anything上没有文件,tomcat会将完整路径作为查询字符串发送到angular应用程序,并且从该查询参数angular处理路由。

2020-06-16