问题描述
我正在为基于 react 的单页应用程序开发一个 spring 后端,其中我使用 react-router 进行客户端路由.
I'm developing a spring backend for a react-based single page application where I'm using react-router for client-side routing.
在 index.html 页面旁边,后端在路径 /api/**
上提供数据.
Beside the index.html page the backend serves data on the path /api/**
.
为了在我的应用程序的根路径 /
上从 src/main/resources/public/index.html
提供我的 index.html,我添加了一个资源处理程序
In order to serve my index.html from src/main/resources/public/index.html
on the root path /
of my application I added a resource handler
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/").addResourceLocations("/index.html");
}
我想要的是在没有其他路由匹配时为 index.html 页面提供服务,例如当我调用 /api
以外的路径时.
What I want to is to serve the index.html page whenever no other route matches, e.g. when I call a path other than /api
.
如何在 spring 中配置这种包罗万象的路由?
How do I configure such catch-all route in spring?
推荐答案
由于我的 React 应用程序可以使用 root 作为前向目标,这最终对我有用
Since my react app could use the root as forward target this ended up working for me
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/{spring:\w+}")
.setViewName("forward:/");
registry.addViewController("/**/{spring:\w+}")
.setViewName("forward:/");
registry.addViewController("/{spring:\w+}/**{spring:?!(\.js|\.css)$}")
.setViewName("forward:/");
}
}
老实说,我不知道为什么必须完全采用这种特定格式以避免无限转发循环.
To be honest I have no idea why it has to be exactly in this specific format to avoid infinite forwarding loop.
这篇关于Spring 捕获 index.html 的所有路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!