React-router"无法GET/*",但根网址除外

Jul*_*enD 26 reactjs react-router

我愿意为我的应用程序使用React-router,我正在尝试首先在doc中给出的示例,我在下面复制了它.现在,当我去localhost:3000/,我看到"App"按预期,但每隔一页,如localhost:3000/inbox返回"无法获取/收件箱".我在这里错过了什么?

var About = React.createClass({
  render: function () {
    return <h2>About</h2>;
}});

var Inbox = React.createClass({
  render: function () {
    return <h2>Inbox</h2>;
}});

var App = React.createClass({
  render () {
    return (
      <div><h1>App</h1>
        <RouteHandler/>
      </div>
)}});

var routes = (
  <Route path='/' handler={App}>
    <Route path="about" handler={About}/>
    <Route path="inbox" handler={Inbox}/>
  </Route>
);
Run Code Online (Sandbox Code Playgroud)

tob*_*obi 59

如果您正在使用,webpack-dev-server则会有一个名为的选项history-api-fallback.如果设置为true404s将回退到/index.html.

将选项添加到devServerWebpack配置的部分,如下所示:

devServer: {
    contentBase: 'app/ui/www',
    devtool: 'eval',
    hot: true,
    inline: true,
    port: 3000,
    outputPath: buildPath,
    historyApiFallback: true,
},
Run Code Online (Sandbox Code Playgroud)

链接到Webpack文档:https://webpack.github.io/docs/webpack-dev-server.html

  • 这是对问题的正确解决方案 (5认同)
  • 谢谢,这就是答案! (3认同)
  • 这应该是经过验证的答案!多谢 ! (2认同)

Bra*_*ugh 17

我相信问题在于您正在制作http资源请求:

GET /inbox HTTP/1.1
Host: localhost:3000
Run Code Online (Sandbox Code Playgroud)

但是只使用客户端路由.您是否打算进行服务器端渲染?您可能需要将路由器位置更改HistoryLocationHashLocation(默认值).

位置道具Router.run告诉它在哪里匹配路线.如果您没有运行服务器端React,我相信您必须使用Router.HashLocation(或者只是将其留空).

如果没有,您将以错误的方式访问您的组件.尝试使用http://localhost:3000/#/inbox.可能需要一点熟悉React-Router,但绝对值得!

反应路由器文档 - HashLocation

  • 这与v2.x已经过时了.请尝试以下允许:https://github.com/reactjs/react-router/blob/master/docs/guides/Histories.md (2认同)