I created a Spring backend with a React front end and used the maven-frontend-plugin to combine both into a single project which I can build into a .jar file.
The problem I encountered is that now React isn't taking precedence over Spring Boot, if that makes sense.
For example, these are the routes I've defined in React using react-router(v6)
<div className="App">
<Routes>
<Route path="/" element={<MainScreen />} />
<Route path="/item/:productId" element={<NewItem />} />
<Route path="/categories/:categoryId" element={<Items />} />
<Route path="/items/search/" element={<Items />} />
<Route path="/items/search/:searchTerm" element={<Items />} />
<Route path="/registration" element={<NewRegistrationScreen />} />
<Route path="/login" element={<LoginScreen />} />
<Route path="/cart" element={<Cart />} />
<Route path="/account" element={<Account />} />
<Route path="*" element={<NotFoundScreen />} />
</Routes>
</div>
And in each of those routes I consume the API served by the backend. But now when I navigate to the url designated in these routes, I get a Whitelabel Error Page indicating that React isn't the one handling that route/url but Spring Boot is.
When I use the Link component from the react-browser-dom it works "normally" as long as the page isn't refreshed. If it is, the same Whitelabel error is shown.
<Link to="/login">To Login</Link>
<Link to="/cart">To Cart</Link>
<Link to="/account">To Account</Link>
Is there any way to fix this problem? Apologies if this isn't properly articulated or explained, this is my first time doing a project like this and the problem is very new to me.
CodePudding user response:
I had to add a controller which redirects the requests so React can handle them.
@Controller
public class RouteController {
@RequestMapping(value = "/{path:[^\\.]*}")
public String redirectSingle() {
return "forward:/index.html";
}
@GetMapping("/*/{path:[^\\.]*}")
public String redirectNested() {
return "forward:/index.html";
}
}
CodePudding user response:
You can try using the BrowserRouter tag and also this route format:
<BowserRouter>
<Routes>
<Route path="/item">
<Route path=":itemId" element={<NewItem/>} />
</Route>
<Route path="/item">
<Route path=":itemId" element={<Item/>} />
</Route>
<Routes>
<BowserRouter />