How To Fix Path Error When A React Build Application Is Deployed In Apache Tomcat

- 1 answer

I have developed a react application and created a production build using "npm run build". When I put this build files in webapps folder(named ldap) of apache tomcat and start the server and go to "http://localhost:8080/ldap/" this link it is showing 404 errors for all static files.

I looked in the network tab and saw that all my static files are served from http://localhost:8080/static/css/main.4e0cec6e.chunk.css it is missing "ldap" part in the link(http://localhost:8080/ldap/static/css/main.4e0cec6e.chunk.css)

Is there a way to solve this error.



Since you are mounting your React app in a subdirectory, you need to tackle a couple of things.

The first would be to set the basename prop in your router, this tells your React app that it will be mounted in a subdirectory.

<Router basename={'/your-directory'}>
  <Route path='/' component={SomeComponent} />

The next thing you need to do is to set the homepage parameter in your package.json file. You set the full URL of your app.

"homepage": ""

And the third and final thing you need to do is update your links and routes.

Example for Route:

<Route path={`${process.env.PUBLIC_URL}/`} component={HomeComponent} />
<Route path={`${process.env.PUBLIC_URL}/other-dir`} component={SomeOtherComponent} />

Example for Link:

<Link to={`${process.env.PUBLIC_URL}/other-dir`}>Link to /other-dir</Link>