【发布时间】:2021-04-24 04:46:18
【问题描述】:
我有一个托管在 S3 中的 react 应用程序。它位于 Cloudfront CDN 后面,可通过自定义域访问:
console.example.com -> CDN -> S3 hosted app
我还有一个无服务器应用程序作为我的后端来处理来自 React 应用程序的 API 调用。这也在 Cloudfront CDN 后面,可通过自定义域访问:
api.example.com -> CDN -> API Gateway
前端已正确配置为指向api.example.com。对于 API 网关,CORS 已启用。
当我导航到主页并尝试登录 console.example.com/login 时,我收到 405 Method Not Allowed 错误。登录,显然是使用POST
我验证了以下 curl 成功,当通过 API Gateway 端点、Cloudfront 域和自定义域访问后端时,有效地排除了任何 API Gateway 问题。
卷曲:
curl --header "Content-Type: application/json" \
--request POST \
--data '{"email":"name@test123.com","password":"xyz"}' \
https://api.example.com/login
在我的研究中,我发现 S3 不支持POST。我还发现了类似的问题,例如this 和this,不幸的是,这对我的情况没有帮助。
还值得注意的是,在本地运行我的前端和后端,工作得很好,让我认为 S3 问题是我的障碍。但我不确定为什么。我的POST 端点没有尝试将对象发布到 S3 存储桶,它们应该使用 bundle.js 文件来访问 api 端点。
那么我错过了什么?虽然我不是前端专家,但我认为其他人在 S3 上托管 react 应用程序并且可以访问他们的 api 就可以了,不是吗?
我故意不包含代码,因为那里有很多要消化的东西,但很高兴包含任何有用的东西,例如 serverless.yml 文件或 cloudformation 模板等。任何帮助都会很棒。
**** 更新 - 为前端 Cloudfront CDN 添加了 Cloudformation 模板 ****
Distribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Origins:
-
# Use the Website as the origin
DomainName: !GetAtt 'Website.DomainName'
Id: !Ref Website
CustomOriginConfig:
HTTPPort: 80
HTTPSPort: 443
OriginProtocolPolicy: https-only
Enabled: true
HttpVersion: http2
DefaultRootObject: index.html
CustomErrorResponses:
- ErrorCode: 404
ResponseCode: 200
ResponsePagePath: /index.html
- ErrorCode: 403
ResponseCode: 200
ResponsePagePath: /index.html
DefaultCacheBehavior:
AllowedMethods:
- DELETE
- GET
- HEAD
- OPTIONS
- PATCH
- POST
- PUT
DefaultTTL: 60
ForwardedValues:
QueryString: true
Cookies:
Forward: none
# The origin id defined above
TargetOriginId: !Ref Website
ViewerProtocolPolicy: "redirect-to-https" # we want to force https
# The certificate to use when using https
Aliases:
- console.example.com
ViewerCertificate:
AcmCertificateArn: arn:aws:acm:us-east-1:11111111:certificate/11111111-fa9b-4705-b9d2-11111111
MinimumProtocolVersion: TLSv1
SslSupportMethod: sni-only
【问题讨论】:
-
您是否允许 API 网关 Cloudfront 分发中的 POST 方法?
-
@cbr 我相信所有方法都是允许的。我测试了直接访问 API 网关,CDN 域和自定义域都按预期返回。当请求来自前端时
-
您使用的是 IAM 身份验证吗?
-
@cbr 我正在使用 Cloudfront 访问身份。我已附上 Cloudformation 模板以供参考
-
是的,但可能不在 API 分发上使用 IAM?
标签: reactjs amazon-s3 react-router serverless-framework http-status-code-405