React-router 直接通过路径访问或刷新页面报错

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

我已经毫无问题地实现了 react-router,它工作正常,但由于某种原因,在用户刷新页面或尝试通过我的路径直接访问主页面的不同页面的情况下收到类似 Cannot GET /whatever 的错误(例如 Cannot GET /blog)。

代码如下:

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

知道我该如何修复它。

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"

从您的路线中删除“/”。直接调用组件。 例如: {

<Route component={ App } path='/master'>
        <Route path = 'board' component={BoardView} />
        <Route  path = 'team'  component={View} />
        <Route path = 'all' component={All} />
        <Route path = 'shots' component={Shots} />
        <Route path = 'home' component={Home} />
        <Route path = 'topper' component={Toppers} />
        <Route path = 'overlay' component={Overlay} />
        <Route path = 'earn' component={Earn} />

}

问题是您的服务器路由器(nginx、Apache...)不知道要 return 什么以及要将什么内容传送到您的浏览器。基本上,如果您的应用程序只是您已经捆绑的前端应用程序,承认您正在使用 nginx,则您的服务器需要这种配置:

server {

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

然后,当您尝试直接转到路由时,您的服务器将始终 return 包含您的 javascript 包的 html 页面,并且 react-router 应该处理其余部分。

请参阅 react-router

文档中的 this explanation