Spring Boot / Angular 4-应用中的路由会触发服务器 [英] Spring Boot/Angular 4 - Routing in app hits the server
问题描述
我有一个Angular 4(ES6)应用程序,该应用程序想从Spring Boot应用程序中提供。我的Angular应用程序具有index.html,当点击 http:// localhost:8080 的地址时,Spring Boot知道映射到Angular中映射到 / search的index.html文件。
I have an Angular 4 (ES6) app that I want to serve from a Spring Boot application. My Angular app has an index.html, and when the address of http://localhost:8080 is hit, Spring Boot knows to map to the index.html file which in Angular is mapped to "/search".
但是,我有另一条称为 adminlogin的路由,可以通过
However, I have another route called "adminlogin" which I would access through
http:// localhost:8080 / adminLogin
但是在这种情况下,它命中了我的Spring Boot应用程序,该应用程序没有映射,然后引发了错误。
But in this instance, it hits my Spring Boot application, which doesn't have a mapping and then it throws an error.
如何获取我的 http:// localhost:8080 / adminLogin 的地址以转到我的Angular应用程序?
How do I get my address of http://localhost:8080/adminLogin to go to my Angular app?
推荐答案
我的SpringBoot 2和Angular6应用程序也遇到了类似的问题。我实现了 WebMvcConfigurer
接口以覆盖 addResourceHandlers()
方法并重定向到 index.html
在spring控制器中找不到映射。这可以在Spring boot 1.5.x中扩展(现已弃用) WebMvcConfigurerAdaptor
类来完成。在以下stackoverflow线程中对此进行了详细讨论: https://stackoverflow.com/a/46854105/2958428
我使用<$ c $中的 outputPath
字段将构建的角度应用程序放在此位置 target / classes / static
c> angular.json (以前为 .angular-cli.json
)。
这是示例代码:
I had the similar issue with my SpringBoot 2 and Angular6 app. I implemented the WebMvcConfigurer
interface to override addResourceHandlers()
method and redirect to index.html
when there were no mappings found in spring controllers. this can be done in Spring boot 1.5.x extending the (now deprecated) WebMvcConfigurerAdaptor
class. this is discussed in details in this stackoverflow thread: https://stackoverflow.com/a/46854105/2958428
I put my built angular app in this location target/classes/static
using the outputPath
field in angular.json
(previously .angular-cli.json
).
Here's the sample code:
@Configuration
public class MyAppWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**/*")
.addResourceLocations("classpath:/static/")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
Resource requestedResource = location.createRelative(resourcePath);
return requestedResource.exists() && requestedResource.isReadable() ? requestedResource : new ClassPathResource("/static/index.html");
}
});
}
}
这篇关于Spring Boot / Angular 4-应用中的路由会触发服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!