本文介绍了使用 spring boot 托管单页应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试在使用 spring 的普通 REST API 旁边托管一个单页应用程序.

So I am trying to host a Single Page Application alongside a normal REST API with spring.

这意味着所有发送到普通 /api/ 端点的请求都应由相应的控制器处理,所有其他请求应定向到文件夹 /中的资源静态/内置

What this means is that all requests that goes to the normal /api/ endpoints should be handled by the respective controller and all other requests should be directed to the resources in the folder /static/built

我通过捕获所有 NoHandlerFoundExceptions 并重定向到 js 文件或 html 文件来实现这一点.然后使用 WebMvcConfigurer 来映射静态内容.

I have gotten this to work by catching all NoHandlerFoundExceptions and redirecting to either the js file or the html file. And then used a WebMvcConfigurer to map the static content.

但这一切对我来说似乎是一种黑客行为,那么有没有一种不那么黑客的方法呢?

But this all seems like a hack to me, so is there a less hacky way of doing it?

推荐答案

通过添加以下映射,设法让 React+ReactRouter 应用程序正常工作:

Managed to have React+ReactRouter app working by adding following mapping:

@Controller
public class RedirectController {

  @GetMapping(value = {"/{regex:\\w+}", "/**/{regex:\\w+}"})
  public String forward404() {
    return "forward:/";
  }

}

这灵感来自 https://stackoverflow.com/a/42998817/991894

这篇关于使用 spring boot 托管单页应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 18:40