我有后端 spring boot 应用程序和使用 angular4 开发的前端。由于这 2 个在部署时在不同的端口 (8080,4200) 上运行,因此它不显示任何 UI。在本地,使用下面的方式启动 Angular 服务器在 localhost:4200 上绝对可以正常工作并显示 web 界面:
ng serve --proxy-config proxy.conf.json
proxy.conf.json 的内容:
{
"*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
但在尝试与 springboot 应用程序 (localhost:8080) 集成时不是。可能需要在部署之前烘焙 ng 业务逻辑(节点/npm 安装等)。
所以我用了ng build
它将生成的文件复制到输出目录 - src/main/resources/static,现在它位于 spring-boot 应用程序路径中。在 localhost:8080 上启动 tomcat 仍然没有显示 UI。我确实在 chrome 选项卡上看到了 Angular 符号/图标,但在 html 页面上没有显示任何内容。
我还添加了一个 Controller 方法来返回 index.html,以便它可以提供路径中的静态文件。
@GetMapping("/")
public String index() {
return "forward:/index.html";
}
但是这样做只会在网页上显示“forward:/index.html”字符串而不是 html 内容。
我是否需要更改此 index.html 中的某些内容,以便它可以路由到我创建的 ng 组件?
不知道在 index.html 中更改选择器是否重要。由于我的主要组件不是应用程序组件(默认情况下是根组件)而是登录组件,所以在 index.html 中我更改了 <app-root></app-root>
登录组件的选择器 <app-login></app-login>
;用户界面中仍然没有任何显示。
似乎 spring-boot 无法理解 Angular 东西以及如何路由到主要的 ng 组件。
下面是index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello App</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script></body>
</html>
项目结构:
-src
-main
-java
- backend
- AppController
- AppService
- Main.java
- frontend
- src
- index.html
- app
-login
- login.component.html
- login.component.css
- login.component.ts
etc..
- resources
- static
- index.html
- application.properties
- ...
部署时如何让前端与后端服务器协同工作?我是否需要在 application.properties 中添加任何参数或配置,以便应用程序在启动时提供来自/resources 的静态内容?我是否添加任何 resourceLocationHandler 来提供服务?
任何帮助,非常感谢!
最佳答案
请用存档工具打开 jar 文件,看看里面是否有静态文件。如果它们可用,您需要告诉 Spring 您在地址栏中输入的 URL 实际上是 Angular 路由:
@Controller
public class Routing {
@RequestMapping({ "", "/login", "/products/**" })
public String gui() {
return "forward:/index.html";
}
}
关于java - 如何将 Angular 与 Spring Boot 集成以在 Spring Boot 端口上查看 Angular Web 界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52079379/