我在我的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;
当我导航到 localhost:8080
时使用 webpack-dev-server 我可以正确显示我的索引路由。但是当我导航到localhost:8080/login' it shows error
时无法获取/登录`。
有什么解决办法吗?
最佳答案
默认情况下,服务器将在 /login
路由中查找 html 文件。因此,您应该将其配置为 html5 导航,以返回它收到的任何路由的 index.html
。
编辑:
要在 webpack 中执行此操作,正如您在评论中建议的那样,您可以将其添加到您的 webpack 开发服务器配置中:
historyApiFallback: true
index.html
应该是默认的,所以不需要指定它。
另请注意,包含点的 URL 仍指向文件,因此会重定向到服务器。例如,如果您有一个诸如 /search/firsname.lastname
之类的 url,则需要为此添加一个处理程序。
historyApiFallback: {
rewrites: [
{
from: /^\/search\/.*$/,
to: function() {
return 'index.html';
}
}
]
},
参见this issue了解更多信息。
关于javascript - react 路由器 : Failed to Navigate Route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40298739/