React-Routing on Heroku won't work

John Diaz
John Diaz used Ask the Experts™
on
Hi EE,

At the moment, I'm hosting my website on Heroku, and have come about a very frustrating issue I don't know how to approach.

My app uses React.js and Node.js -
In the index file (server.js), the following logic is used:

const express = require('express');
const fs = require('fs');
const path = require('path');

var app = express();
var PORT = process.env.PORT || 3001;

if ( process.env.NODE_ENV === "production" ) {
  app.get( '/*',  function ( req, res )  {
    app.use(  express.static("client/build")  );//This is the index.html that was build with React
  });
};

app.listen(PORT, ()=>console.log('listening on port ' + PORT))

Open in new window


What the code does :
If we are in production, grab the build that was made in React.js and render it.

Here comes the problem..

When on the homepage,(  `/` )it renders perfectly.
But when we try to go somewhere like `about` or `contact`, Heroku will give me an error, because it thinks I'm making a request to the back end.

The React routing looks something like this:
class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
        <Route exact path='/' component={Landing}/>
        <Route path='/blogs' component={Blogs}/>
        <Route path='/blog' component={Blog}/>
        <Route path='/contact' component={Contact}/>

        <Route path="/ping" component={Pong} />
        </Switch>
      </BrowserRouter>
    );
  }
}

Open in new window


Any insights into dealing with this deadly bug are greatly appreciated
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
Try

 <Route exact path='`/' component={Landing}/>
        <Route path='~/blogs' component={Blogs}/>
        <Route path='~/blog' component={Blog}/>
        <Route path='~/contact' component={Contact}/>
        <Route path="~/ping" component={Pong} />

Open in new window

Mikkel SandbergWeb Developer

Commented:
Is your entry point (index.html) at the root of the server? If not, you may need to specify a "homepage" in your package.json and rebuild the project. Are you using create-react-app?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial