我有一个 Angular 4 (ES6) 应用程序,我想从 Spring Boot 应用程序提供服务。我的 Angular 应用程序有一个 index.html,本地址为 http://localhost:8080 时被击中时,Spring Boot 知道映射到 index.html 文件,该文件在 Angular 中映射到“/search”。
但是,我有另一个名为“adminlogin”的路由,我可以通过它访问
http://localhost:8080/adminLogin
但在这种情况下,它命中了我的没有映射的 Spring Boot 应用程序,然后它抛出了一个错误。
如何获得我的地址 http://localhost:8080/adminLogin转到我的 Angular 应用程序?
最佳答案
我的 SpringBoot 2 和 Angular6 应用程序也遇到了类似的问题。我实现了 WebMvcConfigurer
接口(interface)来覆盖 addResourceHandlers()
方法,并在 spring Controller 中找不到映射时重定向到 index.html
。这可以在扩展(现已弃用)WebMvcConfigurerAdaptor
类的 Spring boot 1.5.x 中完成。在此 stackoverflow 线程中对此进行了详细讨论:https://stackoverflow.com/a/46854105/2958428
我使用 angular.json
中的 outputPath
字段(以前是 .angular -cli.json
).
这是示例代码:
@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");
}
});
}
}
关于java - Spring Boot/Angular 4 - 应用程序中的路由命中服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46148843/