[英]Unable to fetch images from cloudfront cdn using fetch API in the browser
我不斷收到TypeError: Failed to fetch
when using fetch
API to get images from my cloudfront cdn. A sample URL that demonstrates this problem is https://cdn.dev.textras.com/videos/thumbnails/614fc78597910a00134de449/073be298-4ee4-4521-94fb-f7e0b131d999/screenshot-1.jpg?w=320&q=100&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYxNTkwNDMwODA3NDUzMDAxM2Y4ZTY1YyIsImNvdW50cnlDb2RlIjoiTkdBIiwiaWF0IjoxNjQyMDAzNzUyLCJleHAiOjE2NDIyNjI5NTJ9.mZ8TPa-OQOfpCWPXYYKPQvFyEA-UigpLs13vhQGuuME
如果您使用該 url 作為<img>
標記的src
,則會加載圖像。 如果您在瀏覽器選項卡中訪問 URL,則會加載圖像。 如果您在同一選項卡中打開開發工具,然后執行fetch
請求以獲取圖像(即相同來源),則fetch
請求成功。 如果您從終端使用 postman 或curl
請求圖像,則請求成功。 但是,如果您在一個域與我的 cdn 不同(即跨域)的瀏覽器選項卡中,它不會加載。 這似乎是一個經典的 CORS 問題。 這是定義雲端分發行為的模板片段。 我只包括定義影響此特定圖像的行為的部分:
...
CloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Aliases: !Ref AliasesParam
Comment: !Ref Comment
CacheBehaviors:
- AllowedMethods: "DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT"
CachedMethods: "GET,HEAD,OPTIONS"
Compress: false
PathPattern: 'videos/thumbnails/*'
DefaultTTL: "1814400"
ForwardedValues:
QueryString: true
QueryStringCacheKeys:
- w
- h
- t
- q
- v
LambdaFunctionAssociations:
- EventType: 'viewer-request'
LambdaFunctionARN: !Ref ViewerRequestFunctionVersionArn
- EventType: 'origin-request'
LambdaFunctionARN: !Ref LambdaVideoPathEdgeVersionArn
- EventType: 'origin-response'
LambdaFunctionARN: !Ref OringResponseFunctionVersionArn
MaxTTL: 31536000
MinTTL: 0
SmoothStreaming: false
TargetOriginId: !Ref IdParam
ViewerProtocolPolicy : "redirect-to-https"
# TrustedSigners:
# - String
該模板未指定響應 header 策略,因此我嘗試直接從雲端儀表板設置托管 CORS 策略之一。 我嘗試了SimpleCORS
和CORS-with-preflight-and-SecurityHeadersPolicy
(即托管策略的兩端),但問題仍然存在。
我還查看了TypeError
的可能原因列表,我認為這只能歸因於響應,因為請求有效,除非我從具有不同源域的瀏覽器選項卡請求。
關於問題可能是什么的任何想法? 謝謝!
您可能必須為 HTTP 請求啟用OPTIONS
方法。 正確啟用 CORS 后,這是必需的。 關注此博客了解更多詳情: https://aws.amazon.com/premiumsupport/knowledge-center/no-access-control-allow-origin-error/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.