Search code examples
javascriptreactjsurlflaskurl-routing

Can't reload React page without /#/


I can go to the root route at my site and navigate to different pages just fine without the "/#/" in the url. But when I refresh, it gives me the 404 page.

For example, https://kaisinlipersonal.herokuapp.com/. If you go to the portfolio page, there isn't a hash in the url, and everything seems fine. The url is https://kaisinlipersonal.herokuapp.com/portfolio. But if you refresh while on the portfolio page, https://kaisinlipersonal.herokuapp.com/portfolio gives a 404. Same for all other pages.

Any idea why this is the case?

My routes file:

import React from 'react';
import { IndexRoute, Router, Route, browserHistory } from 'react-router';

import Main from './components/Main';
import Home from './components/Home';
import Portfolio from './components/Portfolio';
import Contact from './components/Contact';
import Blog from './components/Blog';

export default (
    <Router history={browserHistory}>
      <Route path='/' component={Main}>
        <IndexRoute component={Home}/>
        <Route path='/portfolio' component={Portfolio} />
        <Route path='/blog' component={Blog} />
        <Route path='/contact' component={Contact} />
      </Route>
    </Router>
);

The react-route I use is version 3.


Solution

  • The hash (https://kaisinlipersonal.herokuapp.com/#hash) is handled by the client. The server never even knows what the hash is.

    That means https://kaisinlipersonal.herokuapp.com/#hash is really a request to https://kaisinlipersonal.herokuapp.com/. That's where your index page is.

    When you request https://kaisinlipersonal.herokuapp.com/profile, you're no longer loading the index page. But you need to load the index page because it has to handle the URL.

    So to fix that, you need to tell your server to redirect all requests to /, the index file.

    Unfortunately, I do not have experience with Python/Flask (I believe you use that as the server for your profile), but there should be some way to do this using that framework.