Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router with http-server

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 ?

like image 487
SayJeyHi Avatar asked Feb 04 '19 07:02

SayJeyHi


People also ask

What is react router in react?

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.

What is the useroutes hook in react router V6?

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.

What is Static Static router in react router?

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.

How do I add page routing to my react app?

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:


1 Answers

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
like image 162
Raviteja VK Avatar answered Nov 15 '22 12:11

Raviteja VK