we use react-roucter-dom
with http-server
, when user loads main page and click navigation links , new pages will loaded perfectly , but when user refresh page in that route , it returns 404 .
It means HTML5 pushState
is not working with http-server
.
example :
<Router>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</Router>
If user go to /about
page and refresh it , 404 error will happen
Is there a way to fix this issue ?
First created in 2014, React Router is a declarative, component based, client and server-side routing library for React. Just as React gives you a declarative and composable API for adding to and updating application state, React Router gives you a declarative and composable API for adding to and updating the user's navigation history.
React Router v6 comes with a useRoutes Hook that makes collocating your routes into a central route config not only possible, but also simple with a first class API. Say we had the following paths in our application. Typically if you wanted to map those paths to different React components, you'd render something like this.
StaticRouter, as the name implies, is useful in environments where the app's location never actually changes, like when rendering a single route to static HTML on a server. Now that you know how to enable React Router via the BrowserRouter component, let's look at how you can actually tell React Router to create a new route.
Create React App doesn't include page routing. React Router is the most popular solution. To add React Router in your application, run this in the terminal from the root directory of the application: Note: This tutorial uses React Router v6. If you are upgrading from v5, you will need to use the @latest flag:
Use this when you run http-server :
http-server --proxy http://localhost:8080? ./build
It is redirecting any error requests it can't handle to index.html where your react-router configuration resides. If all requests come to this page, then the react-router takes care of routing internally.
By the way, I've built a small script in package.json - scripts , to call all this and serve the build folder like this :
scripts: {
...
"serveprod": "npm run build && http-server --proxy http://localhost:8080? ./build"
...
}
And just run :
npm run serveprod
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With