SeyAde
SeyAde

Reputation: 45

react router dom trailing slash gives error instead of going to 404 page

I'm using a react-router-dom via Route component. Everything works fine, including if a page doesn't exist, then the app goes to a 404 page. All good, until I add a slash at the end of a url and the screen goes blank with 404 errors in the console. For example, this http://localhost/random doesn't exist and goes to a 404 page but as if I do http://localhost/random/ <--- this slash, it breaks everything. What I expect is for this url to also go to 404 page or go to an existing page:

<Switch>
  <Route exact path="/path-extra">
    <Redirect to="/path-redirected" />
  </Route>
  <Route
    path="/path-one"
    component={PathOne}
  />
  <Route
    path="/path-two"
    component={PathTwo}
  />
  <Route render={() => <RoutingError errorCode="404" />} />
</Switch>

The error I receive in the console, if I type http://localhost/random/:

GET http://localhost/js/main.5d5472a1.bundle.js?f6bb2549a0dc1a3342b0 net::ERR_ABORTED 404 (Not Found)

Is there a way to make sure that any path, whether with a slash at the end or not, doesn't break anything and act accordingly?

Upvotes: 0

Views: 930

Answers (1)

Harshith Ramu
Harshith Ramu

Reputation: 21

I faced the similar issue and found out that i had missed adding public path in webpack config. Adding public path helps webpack to understand the root of our project. Following fix worked for me:

output: { publicPath: '/' }

Upvotes: 2

Related Questions