18

我正在使用从https://github.com/facebookincubator/create-react-app创建的 ReactJS SPA

我正在使用 S3 和 Cloudfront 为我的网站提供服务。一切正常,直到我重新加载页面 - 它抛出一个错误(在我的情况下访问被拒绝),因为它无法在没有 Hashbang 的情况下处理。

注意:如果我输入带有 hashbang 的 URL,它可以正常工作

所以本质上,这有效:https://example.com/#/dashboard(重定向到https://example.com/dashboard

但是如果我刷新页面,它会给出如下错误:

在此处输入图像描述

我们使用 browserHistory 来维护路由。我只显示相关代码:

<Router history={browserHistory}>
<Route path='/dashboard' component={Dashboardpage} />
</Router>
4

2 回答 2

58

当您请求https://example.com/dashboard时,第一个请求即https://example.com会发送到服务器,它应该返回包含您的 react-router 的 index.html,它足够聪明,可以理解路径即没有hashbangs并加载所需的组件。因此必须在服务器端设置一些重定向路由。

在您点击https://example.com/dashboard的情况下,S3 和 cloudfront 应该处理错误代码(即 404 或任何)并将页面重定向到 index.html,之后 react-router 将处理哪个组件装载。

在此处输入图像描述

在此处输入图像描述

希望我的回答很清楚;)

你也可以参考这里给出的答案React-router urls don't work when refresh or writting manual

于 2017-02-15T10:06:54.967 回答
1

除了 Shailaja 解释的错误页面设置之外,请确保您的 CloudFront 分配指向网站端点而不是 api 端点。API Endpoints 无法与 react-router 一起正常工作。

API端点:

bucket-name.s3-website-region.amazonaws.com

网站端点:

存储桶名称.s3-website.region.amazonaws.com

于 2019-11-18T12:51:27.447 回答