0

This is probably more of a server issue than an issue with React Router, but here is the scenario I'm stuck with:

When developing my app on my local machine, say I wish to navigate to the route /about. So for example, I can enter localhost:3000/about and hit enter, and the page will load and show the "about" component.

But after building the app and deploying it on my server, if the user physically types http://example.com/about (assuming my site is example.com) and hits enter in the URL bar, it returns the Server Error 404 - file or page not found error. How can I get it to simply load the about component instead of trying to navigate to an "about" page that doesn't exist?

sme
  • 4,023
  • 3
  • 28
  • 42
  • You can use react router without needing to have explicit path, it can also work with hash history – Axnyff Mar 03 '18 at 16:25
  • @Axnyff The issue I'm dealing with is deep-linking, if the user clicks on a that navigates to the /about component, there is no issue. Its only an issue if the user actually submits the URL address in the address bar. – sme Mar 03 '18 at 16:27
  • @sme: you either need to make your server accept all routes or you can simply fix it on the client side by using hash paths instead of direct path – Axnyff Mar 03 '18 at 16:30

1 Answers1

0

I'm not sure what type of server tech you are using. With BrowserRouter in react-router you need to make sure your server sends back the index.html when you ask for /about.

This is an example I would use in express:

app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, '../build', 'index.html'));
});

When someone goes to /about it will send back index.html and then your routing will be managed by react-router from that point.

webpack-dev-server does this for you when you use the historyApiFallback. https://webpack.js.org/configuration/dev-server/#devserver-historyapifallback

jens
  • 2,075
  • 10
  • 15
  • the question is tagged [tag:iis], so it's likely the server is a microsoft iis server..... – Claies Mar 03 '18 at 16:30
  • Ahh good catch. Then setup the IIS server to send back the index.html for all routes that aren't handled. – jens Mar 03 '18 at 16:31