React Routing works locally, but not Heroku

My problem here is incredibly similar, if not quite the same as in this problem. Unfortunately, I could not solve it using the strategy that it provides. So here are my own details:

I use the Create React App, React Router 4, Express, and Heroku and follow the instructions here regarding setting up a server with CRA.

Locally, I can access routes such as myapp/about , but after creating and clicking on the hero, these 404.

I can navigate this route through the user interface (for example, by clicking on a menu item that clicks the route on history ), but I cannot go to this route using only my browser address bar. In addition, when I navigate using the user interface, I do not see network activity associated with a route such as the /about request. However, when I change the address bar and press enter, it gives a network request to the specified route.

Here are some code snippets from my code:

app.js

 <Switch> <Route exact path="/about" component={About} /> <Route path="/" render={props => <coolListContainer {...props}/>} /> </Switch> 

server.js

 if (process.env.NODE_ENV === 'production') { app.use(express.static('client/build')); } //...what some of my api routes look like: app.route('/api/verify') .post( async (req, res) => { try { await db.verifyCode(req.body) res.json('success') } catch (err) { res.json(err); } } }); 

My directory structure , as shown in the full version .

 └── myapp  ├── Procfile  ├── README.md  ├── client  │  ├── build  │  │  ├── asset-manifest.json  │  │  ├── index.html  │  │  └── static  │  │  ├── css  │  │  │  ├── main.e8c50ca0.css  │  │  │  └── main.e8c50ca0.css.map  │  │  └── js  │  │    ├── main.24fe0ebe.js  │  │    └── main.24fe0ebe.js.map  │  ├── package.json  │  ├── public  │  │  └── index.html  │  ├── src  │  │  ├── About.js  │  │  └── index.js  │  └── styles  │     └── about..css  ├── package.json  ├── server.js  └── static.json 

In response to this post, I also put the static.json file in the root directory.

static.json

 { "root": "client/build/", "clean_urls": false, "routes": { "/**": "index.html" } } 

The above configuration gives me 404s on any route.

+5
source share
1 answer

Ok, I figured it out.

All I need to do is make sure that any request that is not related to my internal API, such as a GET request through the address bar, is sent directly to my index.html file, which handles dynamic routing through the React Router. It seems obvious now.

Here is the last route in my app.js :

 app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '/client/build/index.html')); }); 
+5
source

Source: https://habr.com/ru/post/1269159/


All Articles