我正在使用React-router,当我点击链接按钮时,它工作得很好,但当我刷新我的网页时,它没有加载我想要的东西。

例如,我在localhost/joblist和一切都很好,因为我到达这里按下一个链接。但如果我刷新网页,我会得到:

Cannot GET /joblist

默认情况下,它不是这样工作的。最初我有我的URL localhost/#/和localhost/#/joblist,他们工作得很好。但我不喜欢这种类型的URL,所以试图删除#,我写道:

Router.run(routes, Router.HistoryLocation, function (Handler) {
 React.render(<Handler/>, document.body);
});

这个问题不会发生在localhost/,这个总是返回我想要的。

这个应用程序是单页的,所以/joblist不需要向任何服务器询问任何事情。

我的整个路由器。

var routes = (
    <Route name="app" path="/" handler={App}>
        <Route name="joblist" path="/joblist" handler={JobList}/>
        <DefaultRoute handler={Dashboard}/>
        <NotFoundRoute handler={NotFound}/>
    </Route>
);

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

当前回答

我们使用Express.js的404处理方法。

// Path to the static React build directory
const frontend = path.join(__dirname, 'react-app/build');

// Map the requests to the static React build directory
app.use('/', express.static(frontend));

// All the unknown requests are redirected to the React SPA
app.use(function (req, res, next) {
    res.sendFile(path.join(frontend, 'index.html'));
});

这招很管用。现场演示是我们的网站。

其他回答

修复在刷新或直接调用URL时“不能GET /URL”的错误。

配置你的webpack.config.js,以期望给定的链接像这样的路由。

module.exports = {
  entry: './app/index.js',
  output: {
       path: path.join(__dirname, '/bundle'),
       filename: 'index_bundle.js',
       publicPath: '/'
  },

如果你在IIS中托管:将此添加到我的webconfig解决了我的问题

<httpErrors errorMode="Custom" defaultResponseMode="ExecuteURL">
    <remove statusCode="500" subStatusCode="100" />
    <remove statusCode="500" subStatusCode="-1" />
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="404" path="/" responseMode="ExecuteURL" />
    <error statusCode="500" prefixLanguageFilePath="" path="/error_500.asp" responseMode="ExecuteURL" />
    <error statusCode="500" subStatusCode="100" path="/error_500.asp" responseMode="ExecuteURL" />
</httpErrors>

您可以为任何其他服务器进行类似的配置。

用Laravel在React中实现JavaScript SPA的解决方案

公认的答案是对为什么会发生这样的问题的最好解释。如前所述,您必须同时配置客户端和服务器端。

在你的blade模板中,包括JavaScript绑定文件,确保像这样使用URL外观:

<script src="{{ URL::to('js/user/spa.js') }}"></script>

在路由中,确保将此添加到刀片模板所在的主端点。例如,

Route::get('/setting-alerts', function () {
   return view('user.set-alerts');
});

以上是刀片模板的主要端点。现在再添加一条可选路线,

Route::get('/setting-alerts/{spa?}', function () {
  return view('user.set-alerts');
});

发生的问题是,首先加载刀片模板,然后加载React路由器。当你加载'/setting-alerts'时,它会加载HTML内容和JavaScript代码。

但是当你加载'/setting-alerts/about'时,它首先在服务器端加载。因为它在服务器端,所以这个位置上没有任何东西,并且它返回not found。当你有可选的路由器时,它加载同一个页面,React路由器也被加载,然后React加载器决定显示哪个组件。

将此添加到webpack.config.js:

devServer: {
    historyApiFallback: true
}

当我在Electron中使用React作为前端,使用React -router-dom作为路由时,我就遇到了这个问题。

我用HashRouter替换了BrowserRouter,这是固定的。

这里有一个简单的例子:

import {
  HashRouter as Router,
  Switch,
  Route,
} from "react-router-dom";