Allow AJAX GETs from Amazon S3? (Access-Control-Allow-Origin)

后端 未结 11 1801
灰色年华
灰色年华 2020-12-23 16:34

I\'m storing JSON objects in Amazon S3, and I\'d like to load that data directly from S3 from Javascript. My GET looks pretty generic:

$.ajax({
    \'type\':         


        
相关标签:
11条回答
  • 2020-12-23 17:27

    You may want to increase the MAX AGE configuration if you have larger files that will take longer to download, or they may cut off early. Media hosting etc will need this. My config for wildcard access (any domain) was 10000 seconds max, which should be safely longer than anyone needs to download my files even on a bad connection:

    <?xml version="1.0" encoding="UTF-8"?>
    <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <MaxAgeSeconds>10000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    </CORSConfiguration>
    
    0 讨论(0)
  • 2020-12-23 17:30

    S3 doesn't send the 'Access-Control-Allow-Origin' header if you use the wildcard * like:

    <AllowedOrigin>*</AllowedOrigin>
    

    To force s3 sending the AllowedOrigin header but still let your content be loaded from any site, use this:

    <AllowedOrigin>http://*</AllowedOrigin>
    <AllowedOrigin>https://*</AllowedOrigin>
    
    0 讨论(0)
  • 2020-12-23 17:34

    You can use a jsonp request instead of json. Here are the details. http://api.jquery.com/jQuery.ajax/

    0 讨论(0)
  • 2020-12-23 17:35

    For my case, I want to GET some resources from a bucket "myBucket".

    On the S3 client side, AWS S3 now support JSON to configure CORS policies [ref]

    Bucket Policy:

    [
        {
            "AllowedHeaders": [
                "*",
                "x-amz-*"
            ],
            "AllowedMethods": [
                "GET",
                "HEAD"
            ],
            "AllowedOrigins": [
                "*"
            ],
            "ExposeHeaders": []
        }
    ]
    

    On server-side / client side (JQUERY Ajax)

    $.ajax({
        type: "GET", 
        url: "https://myBucket/myObject",
    });​​​​​​​​​​​​​​​
    

    Try it!, hope it helps!

    0 讨论(0)
  • 2020-12-23 17:38

    This is my Tip from: https://github.com/mozilla/pdf.js/issues/3150

    <?xml version="1.0" encoding="UTF-8"?>
    <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
        <CORSRule>
            <AllowedOrigin>*</AllowedOrigin>
            <AllowedMethod>GET</AllowedMethod>
            <AllowedHeader>*</AllowedHeader>
            <ExposeHeader>Accept-Ranges</ExposeHeader>
            <ExposeHeader>Content-Range</ExposeHeader>
            <ExposeHeader>Content-Encoding</ExposeHeader>
            <ExposeHeader>Content-Length</ExposeHeader>
        </CORSRule>
    </CORSConfiguration>
    
    0 讨论(0)
提交回复
热议问题