反应路由器:无法导航路由

时间:2016-10-28 05:41:49

标签: javascript reactjs webpack react-router webpack-dev-server

我在index.js文件中设置了简单的路由。

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')
);

我的App.js

import React, { Component } from 'react';

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

export default App;

当我使用webpack-dev-server导航到localhost:8080时,我可以正确显示我的索引路径。但是当我导航到localhost:8080/login' it shows error无法获取/登录时。

任何解决方案?

1 个答案:

答案 0 :(得分:2)

默认情况下,服务器将在/login路由中查找html文件。因此,您应该为html5导航配置它,以便为它收到的任何路由返回index.html

编辑:

要在webpack中这样做,正如您在评论中所建议的那样,您可以将其添加到您的webpack dev服务器配置中:

historyApiFallback: true 

index.html应该是默认值,因此无需指定它。

另请注意,包含点的网址仍指向文件,因此会重定向到服务器。例如,如果您有一个诸如/search/firsname.lastname之类的网址,则需要为此添加处理程序。

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

有关详细信息,请参阅this issue