reactjs - 由于 React SPA 中的 Hasbangs,无法在刷新时访问页面

标签 reactjs amazon-s3 amazon-cloudfront hashbang create-react-app

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

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

注意:如果我输入带有 hashbang 的 URL,效果很好

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

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

enter image description here

我们使用 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将处理要加载的组件。

enter image description here

enter image description here

希望我的答案很清楚;)

您也可以引用这里给出的答案React-router urls don't work when refreshing or writting manually

关于reactjs - 由于 React SPA 中的 Hasbangs,无法在刷新时访问页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42221392/

相关文章:

reactjs - 为什么我的 react 路由器调用 api 两次?

angular - 上传到 S3 而不暴露您的 accessKeyId

amazon-cloudfront - Django Compressor - CloudFront 和 manifest.json

reactjs - React Native如何更改ProgressBarAndroid开始颜色和结束颜色

reactjs - 如何在 Webpack 配置文件中将 CSS 名称设置为不是哈希值?

ruby-on-rails - 基于 request.ssl 通过 HTTPS 动态提供文件?附附件

python - 如何使用 boto3 将标签添加到 S3 存储桶而不删除现有标签?

amazon-web-services - 告诉 CloudFront 仅缓存 200 个响应代码

amazon-s3 - ListBucketResult xml 试图通过 CloudFront 在 S3 中显示站点的主页

javascript - 如果语句不能正常工作 [React hooks]