我正在使用从 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>
最佳答案
当您请求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 refreshing or writting manually
关于reactjs - 由于 React SPA 中的 Hasbangs,无法在刷新时访问页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42221392/