在 Tomcat 中刷新后出现 Angular 404 错误
Posted
技术标签:
【中文标题】在 Tomcat 中刷新后出现 Angular 404 错误【英文标题】:Angular 404 error after refresh in Tomcat 【发布时间】:2019-08-06 18:52:37 【问题描述】:Tomcat 刷新后出现 404 错误如何解决?一切正常,直到您转到 http://localhost:8080/login 并刷新您的浏览器。之后,我的应用看不到 Angular 并且确实请求 API。 我有 angular 7 的 spring boot 2 应用程序。我需要添加一些重写规则。
附言我不想使用哈希定位策略。
【问题讨论】:
你必须使用 hashbang URL @Shohel 正如我所说,我正在寻找没有哈希的解决方案 【参考方案1】:我不得不处理一个类似的问题:我正在使用 Angular 6 前端和 Java 后端(REST Web 服务、Spring 和 MyBatis)开发一个 Web 应用程序。
对于 Spring 配置,我还是使用 XML 配置文件。
在开发模式下,我在客户端部分使用4200
端口,在后端使用 8080(在 Tomcat 上)。在这种情况下没有问题。
然后我在 war 中合并了 Angular 应用程序,特别是在 public
文件夹中。之后,当我运行应用程序并点击 F5 按钮时,我会收到一个404 error
。
对于 Spring 端的 public
文件夹,我进行以下配置:
<mvc:resources mapping="/public/**" location="/public/">
<mvc:resource-chain resource-cache="false">
<mvc:resolvers>
<bean class="com.example.web.AngularResourceResolver" />
</mvc:resolvers>
</mvc:resource-chain>
</mvc:resources>
AngularResourceResolver
是这样定义的:
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.resource.PathResourceResolver;
public class AngularResourceResolver extends PathResourceResolver
@Override
protected Resource getResource(String resourcePath, Resource location) throws IOException
Resource requestedResource = location.createRelative(resourcePath);
Resource defaultResource=location.createRelative("/index.html");
Resource resource = requestedResource.exists() && requestedResource.isReadable() ? requestedResource : defaultResource;
return resource;
应用此配置后,即使在 Tomcat 上一切正常,即使按下 F5。
希望对你有帮助。
【讨论】:
谢谢!您的答案应该可以,我找到了几乎相同的解决方案,我将其粘贴在下面。【参考方案2】:正如@xcesco 所回答的,我对spring boot 的最终解决方案:
首先,我已将所有 angular 文件移至静态目录,然后添加:
@Configuration
public class WebMvcConfig 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");
);
【讨论】:
以上是关于在 Tomcat 中刷新后出现 Angular 404 错误的主要内容,如果未能解决你的问题,请参考以下文章