2

I've made a front end in reactjs and back end of application in Spring Boot. When I do npm run build and build a static version of the app to put it in the static folder of Spring Boot application, my Route Paths in react stop working. When I try to get to localhost:8080/choose or localhost:8080/account it says 404 not found, but in normal front end application it works correctly.

import React, {useEffect, useState} from 'react'
import logo from './logo.svg';
import './App.css';
import GoogleLogin from "react-google-login";
import {BrowserRouter, Routes, Route, Navigate} from "react-router-dom";
import Choose from "./Choose/Choose.js";
import Main from "./Main/Main.js";
import Account from "./Account/Account.js";

function App() {
  
  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
          <Route path={'/'} element={
            <Main></Main>
          }
          >
          </Route>
          <Route path={'/choose'} element={
            <Choose></Choose>
          }>
          </Route>
          <Route path={'/account'} element={
            <Account></Account>
          }>
          </Route>
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;

Here's the image of it in browser

aleksandar3
  • 57
  • 1
  • 5

1 Answers1

1

Your Project must be having the api and static page and i believe that static pages is the build of your react app.

Make the mapping of the url in the spring controllers to the /index.html page of your react page

here is example of my app.js and spring controller

App.js

    <BrowserRouter >
  {/* <div>
    <h1 >Dashboard</h1>
  </div> */}
  <Routes>
  <Route path="/" element={<LoginForm/>} />
  <Route path="/dashboard" element={<Dashboard/>} />
  <Route path="/add-new-mobile" element={<AddMobile/>} /> 
  <Route path="/EditMobile" element={<EditMobile/>} />
  <Route path="/SellMobile" element={<SellMobile/>} />
  </Routes>
  
  {/* Add other routes as needed */}
</BrowserRouter>

Controller.java

@Controller
@RequestMapping("/")
public class StaticWebController {

@RequestMapping("/Dashboard")
 public ModelAndView  toDashBoardPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
     return new ModelAndView("forward:/");
}

@RequestMapping("/add-new-mobile")
 public ModelAndView  someOtherPage(HttpServletRequest request,    HttpServletResponse response) throws IOException {
     return new ModelAndView("forward:/");
  }

}

The url content when the brower hits the //url/Dashboard will go to the react app / root page which will handle the Dashboard and present the page . It need more explanation from some expert how does React static page will convert and handle the request.

I hope it helps

Killerbeans
  • 1,903
  • 2
  • 10
  • 7