如何解决“x-cache: Error from cloudfront"在SPA上 [英] How to solve "x-cache: Error from cloudfront" on SPA

查看:50
本文介绍了如何解决“x-cache: Error from cloudfront"在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 并且 react router 将获得正确的路由.

The CDN will redirect all the 404/403 errors to the main index.html and react router will get the correct routing.

我们有我们的网站,并且客户端路由器工作正常,但是我们的 CDN 的响应有问题 x-cache: Error from 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:

如果我们访问主 URL https://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 时,请求将命中 index.html 文件在 S3.然后您可以单击一个按钮并转到 http://mywebsite.com/stats,这是您的 SPA 应用程序的内部路由.因此,它不会触发任何后端请求.

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 SPA app. Thus, it will not trigger any backend request.

但是如果您重新加载页面,http://mywebsite.com/stats 将被发送到 S3,因为您的浏览器不知道您正在运行 SPA 前端.

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 an SPA frontend.

S3 将返回带有 index.html 的 403 错误,Cloudfront 将向您发送错误.

S3 will return 403 error with index.html and Cloudfront will send 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)
}

来源:https://hackernoon.com/how-to-host-a-single-page-application-with-aws-cloudfront-and-lambda-edge-39ce7b036da2

这篇关于如何解决“x-cache: Error from cloudfront"在SPA上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆