如何解决“ x-cache:cloudfront的错误”?在SPA [英] How to solve "x-cache: Error from cloudfront" on SPA
问题描述
我们在尝试使SPA与客户端路由器(反应路由器)一起工作时遇到问题。我们使用的是 DOMAIN->概念。 CDN(CloudFront)-> S3
用于提供静态文件。
We are having issues trying to make working a SPA with a client router (react router). We are using the concept of have a DOMAIN -> CDN (CloudFront) -> S3
for serving our static files.
我们已经配置了S3用于提供静态文件。 CDN配置为具有S3的来源,并且我们配置了自定义错误页面以捕获错误:
We have configured the S3 for serving static files. The CDN are configured to have the origin from the S3 and we have configured custom error pages to catch errors:
使用此配置,我们可以捕获如下错误:
with this configuration we can catch errors like this:
https://www.example.com/custom-url
CDN会将所有404/403错误重定向到主要的 index.html
和反应路由器
将获得正确的路由。
The CDN will redirect all the 404/403 errors to the main index.html
and react router
will get the correct routing.
我们已经在工作我们的站点,并且客户端路由器工作正常,但是我们使用 x-cache的CDN响应存在问题:cloudfront错误
:
We have working our site, and the client router is working fine, but we have a problem with the response of our CDN with x-cache: Error from cloudfront
:
如果我们访问主网址 http s://www.example.com
没有任何查询参数(不是查询字符串)都可以正常工作。
If we access to the main url https://www.example.com
without any query param (not query string) all works fine.
如何解决此问题并确保所有动态URL都能正常工作?
How can I solved this problem and make that all my dynamic URLs work?
谢谢。
推荐答案
当您访问 http://mywebsite.com
时,请求将在S3中命中 index.html
文件。然后,您可以单击一个按钮,然后转到 http://mywebsite.com/stats
,这是React应用程序的内部路由。因此,它不会触发任何后端请求。
When you visit http://mywebsite.com
the request will hit the index.html
file in S3. Then you might click a button and go to http://mywebsite.com/stats
which is an internal route of your React app. Thus, it will not trigger any backend request.
但是,如果您重新加载页面,则 http://mywebsite.com/stats
将被发送到S3,因为您的浏览器不知道您正在运行React应用程序。
But if you reload the page, http://mywebsite.com/stats
will be sent to S3 as your browser does not know that you are running a React application.
S3将通过index.html返回403错误,Cloudfront会向您发送错误。
S3 will return 403 error with index.html and Cloudfront will sent you the error.
解决方案在cloudfront中使用了边缘lambda函数。下面是一个示例:
Solution is using an edge lambda function in cloudfront. Here an example:
const path = require('path')
exports.handler = (evt, ctx, cb) => {
const {request} = evt.Records[0].cf
if (!path.extname(request.uri)) {
request.uri = '/index.html'
}
cb(null, request)
}
这篇关于如何解决“ x-cache:cloudfront的错误”?在SPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!