SSuhat SSuhat - 1 month ago 11
Javascript Question

React Router: Failed to Navigate Route

I setup simple route within my index.js file.

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

import reduxThunk from 'redux-thunk';

import '../less/app.less';

import reducers from './reducers';

import App from './components/App';
import Login from './components/auth/Login';
import Welcome from './components/Welcome';

// const defaultSetting = settings;
const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);

ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Welcome} />
<Route path="login" component={Login} />
</Route>
</Router>
</Provider>
, document.querySelector('.container')
);


my App.js

import React, { Component } from 'react';

class App extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}

export default App;


When I navigate to
localhost:8080
using webpack-dev-server I can properly show my index route. but when I navigate to
localhost:8080/login' it shows error
Cannot GET /login`.

Any solution?

Answer

By default the server will look for an html file at the /login route. So you should configure it for html5 navigation to return you index.html for any route it receives.


EDIT:

To do so in webpack, as you suggest in the comments, you can add this to your webpack dev server config:

historyApiFallback: true 

index.html should be the default, so no need to specify it.

Also please note that urls containing dots are still pointing to files and thus redirected to the server. For example, if you have an url such as /search/firsname.lastname you would need to add a handler for this.

historyApiFallback: {
    rewrites: [
        {
            from: /^\/search\/.*$/,
            to: function() {
                return 'index.html';
            }
        }
    ]
},

See this issue for more info.