反应路由器在 aws s3 存储桶中不起作用 [英] react router doesn't work in aws s3 bucket
问题描述
我将我的 React 网站 build/
文件夹部署到 AWS S3 存储桶中.
如果我转到 www.mywebsite.com
,它会起作用,如果我点击 a
标签转到项目"和关于"页面,它会将我带到右边页.但是,如果我复制并发送页面 url 或直接转到以下链接:www.mywebsite.com/projects
,它会返回 404.
这是我的 App.js
代码:
const App = () =>(<路由器><div><导航栏/><开关><路由精确路径="/" component={Home}/><路由精确路径="/projects" component={Projects}/><路由精确路径="/about" component={About}/><路由组件={NoMatch}/></开关>
</路由器>);
2020 年 5 月 1 日更新:
由于这个帖子很活跃,我需要更新答案:
所以你有几个选项可以解决这个问题:
- 您可以将index.html 放在错误文档 框中(就像艾伦·弗里德曼(Alan Friedman)建议的那样).
- 转到您的存储桶(实际拥有代码的存储桶 - 不是您用来重定向的存储桶)-> 属性 -> 静态网站托管:
- 这不是hacky",但它的工作原理是
react-router
工作:它处理来自前端的请求并将用户路由到其他路线,但总体而言,React 应用程序是单页的应用程序. - 如果您想要服务器端 React,请考虑使用 Next.js.
您可以将指定的错误文件 error.html 放在 React 应用的public 文件夹和静态网站托管>:错误文档框,放入:error.html.这也有效.我已经测试过了.
使用 AWS CloudFront > CloudFront 分配 > 存储桶的分配 > 错误页面 并添加您想要的错误代码.如果您不使用
react-router
(如下例所示),存储桶将以 错误 403 响应,因此您可以使用 error.html.
- 对于
TypeScript
,目前react-router
不支持它,所以你应该考虑选项2 和3.他们将根据 6.* 中更新库">这个话题.
I deployed my React website build/
folder into an AWS S3 bucket.
If I go to www.mywebsite.com
, it works and if I click on a
tag to go to Project and About pages, it leads me to the right page.
However, if I copy and send the page url or go straight to the link like: www.mywebsite.com/projects
, it returns 404.
Here's my App.js
code:
const App = () => (
<Router>
<div>
<NavBar/>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/projects" component={Projects}/>
<Route exact path="/about" component={About}/>
<Route component={NoMatch}/>
</Switch>
</div>
</Router>
);
Update 1 May 2020:
Since this post is quite active, I need to update the answer:
So you have a few options to solve the issue:
- You can put index.html in the Error document box (like Alan Friedman suggested).
- Go to your bucket (the one that actually has the code - not the one you use to redirect) -> Properties -> Static website hosting:
- This is not "hacky" but it works because of the way
react-router
works: It handles the requests from the front-end and routes users to other routes but overall, the React app is a single-page application. - If you want server-side React, consider using Next.js.
You can put a designated error file error.html in the public folder of your React app and in the Static website hosting: Error document box, put in: error.html. This also works. I've tested it.
Use AWS CloudFront > CloudFront Distributions > The distribution of your bucket > Error Pages and add the error code you want. If you don't use
react-router
(like the example below), the bucket will respond with Error 403 so you can respond with your error.html.
- For
TypeScript
, currentlyreact-router
doesn't support it so you should consider option 2 and 3. They're going to update the library in future version6.*
according to this thread.
这篇关于反应路由器在 aws s3 存储桶中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!