【问题标题】:React Router: Failed to Navigate RouteReact Router:无法导航路由
【发布时间】:2017-03-10 23:19:37
【问题描述】:

我在我的 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 errorCannot GET /login`。

有什么办法吗?

【问题讨论】:

  • 开发服务器已正确配置为始终返回您的 index.html(即使您请求 /login)?
  • 它不应该总是读取我的 index.js 吗?
  • 尝试使用 &lt;Router history={hashHistory}&gt; 然后访问 localhost:8080/#/login ,使用 browserHistory 我可以从父路由导航,但是当我尝试直接加载页面时出现错误
  • @ShubhamKhatri 嗨,我通过在我的 webpack 配置中添加 historyApiFallback: { index: 'index.html' } 解决了这个问题。我真的不喜欢使用哈希一。但你的建议也有效。谢谢:D

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


【解决方案1】:

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


编辑:

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

historyApiFallback: true 

index.html 应该是默认的,所以不需要指定。

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

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

请参阅this issue 了解更多信息。

【讨论】:

  • 我在我的 webpack 配置中添加了这个方法:historyApiFallback: { index: 'index.html' } 你觉得呢?这是最佳做法吗?
猜你喜欢
  • 1970-01-01
  • 2017-09-21
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 2014-08-09
  • 2018-01-27
  • 2022-11-06
  • 2020-09-11
相关资源
最近更新 更多