Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

reactjs - Getting 403 Access Denied Errors When Hosting a React Router App in AWS S3 and CloudFront

When I deployed a React Router app to AWS S3 and CloudFront and when I try to access React routes directly it gives the following error with 403 error code. I can access both the base URL(www.sample-app.com) and route URLs(www.sample-app.com/cart) when it flows through the app.

But If I try going directly to a React route(www.sample-app.com/cart) it produces a 403 Access Denied error as follows. The major pain point is it produces this error when I try to refresh a React route URL.

<Error>
  <Code>AccessDenied</Code>
  <Message>Access Denied</Message>
  <RequestId>REQUEST_ID</RequestId>   
  <HostId>HOST_ID</HostId>
</Error>

Note: I'm using AWS load balancer and Lambda functions as backend. I have setup AWS ALB and Cloudfront to authenticate users with AWS Cognito.

Appreciate your help on this.

question from:https://stackoverflow.com/questions/65948649/getting-403-access-denied-errors-when-hosting-a-react-router-app-in-aws-s3-and-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like I mentioned in the comment, you can't use <BrowserHistory> when you host in a static site. You need a mechanism to redirect all URLs to your index.html so react-router will take over.

To Achieve this you will need some server-side code and hosting for the same. S3 won't work as it can handle only static files. If S3 is the only option, use or there is a hack mentioned [here][1]. I won't recommend it but there is one.

If you are planning to use server-side code here is an example of how NodeJs Express can be used to get the routing work,

app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', function(req, res) {
    res.sendfile('./dist/index.html');
});

assuming your build is in the dist folder. [1]: react router doesn't work in aws s3 bucket


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...