Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router error accessing directly by the path or refreshing the page

I have implemented react-router without any problem, it's working properly, but for some reason in the case an user refresh the page or try to access directly to a different page of the main one by the path i'm getting an error like Cannot GET /whatever (e.g. Cannot GET /blog).

Below is the code:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import store from 'store';

// Layouts
import App from 'layouts/app';

// Components
import Portfolio     from 'ui/portfolio';
import BlogContainer from 'ui/blog-container';
import TimeLine      from 'ui/timeline';
import About         from 'ui/about'
import Contact       from 'ui/contact'

ReactDOM.render((
  <Provider store={store}>
    <Router history={browserHistory}>

        <Route component={App}>
            <Route path="/" component={Portfolio} />
            <Route path="/blog" component={BlogContainer} />
            <Route path="/timeline" component={TimeLine} />
            <Route path="/about" component={About} />
            <Route path="/contact" component={Contact} />
        </Route>

    </Router>
  </Provider>
), document.getElementById('root'));

Any idea how can I fix it.

Note: dependencies I am using
    "react": "^0.14.3",
    "react-dom": "^0.14.3",
    "react-redux": "^4.0.6",
    "react-router": "^2.0.0",
    "redux": "^3.3.1"
like image 815
gon250 Avatar asked Sep 14 '25 11:09

gon250


1 Answers

The problem is that your server router (nginx, Apache...) does not know what to return and what content to deliver to your browser. Basically, if your app is only a front end app that you have already bundled, admitting you're using nginx, you need this kind of config for your server:

server {

    location / {
        try_files $uri /your/index.html; # the path to your html page
    }
} 

Then, when you will try to go directly to a route, your server will always return the html page containing your javascript bundle, and react-router should handle the rest.

See the this explanation in the docs of react-router

like image 192
martpie Avatar answered Sep 17 '25 00:09

martpie