I am deploying a React application where the build artifacts are placed in the static directory of a Spring Boot application, yet I am encountering 404 Not Found errors when requests are made to the application. As an additional note, I am currently testing this in a local environment.
I deploy the React build artifacts by running the following commands:
$ npm run build
$ rm -rf ../src/main/resources/static/*
$ mv build ../src/main/resources/static/`
I have implemented a single-page application using react-router-dom. Here is the setup for the React router in my application:
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/home" element={<Home />} />
<Route path="/xxx" element={<XXX />} />
</Routes>
</Router>
);
}
export default App;
Spring Boot typically looks for files under the static directory to respond to requests for paths like /home or /hoge. However, since React is used to create a single-page application (SPA), all requests need to be redirected to index.html. To achieve this, I have configured Spring Boot as follows:
@Configuration
public class SpaWebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// Serve all static files from the 'build' directory inside 'static'
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/build/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// Forward all requests to the 'index.html' file
registry.addViewController("/**").setViewName("forward:/index.html");
}
}
However, I am still receiving 404 errors. Why might this be happening?