russelll
russelll

Reputation: 61

How to debug CORS error

I'm trying to grab an image from Amazon S3 using cross-origin resource sharing so that I can use the canvas.toDataUrl() method.

On S3 I set the CORSconfiguration on the bucket to:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

When canvas.toDataURL() threw security error code 18, I guessed it was because the image had to be loaded with a "crossOrigin" attribute set.

Still, no matter how I load the image from S3, for example:

<img src="http://s3.amazonaws.com/storybookstorage/wood.png" crossOrigin="anonymous">

Chrome now gives me the error when I load this image:

Cross-origin image load denied by Cross-Origin Resource Sharing policy.

Can anyone help me figure out what's wrong, or even how I could pinpoint where the problem might be?

My headers for the image request (from chrome dev tools):

Request:

 GET /storybookstorage/wood.png HTTP/1.1
 Host: s3.amazonaws.com
 Connection: keep-alive
 Cache-Control: max-age=0
 Accept: image/webp,*/*;q=0.8
 If-None-Match: "d5098b2c3d1417da8ccd9764612248ca"
 If-Modified-Since: Thu, 08 Aug 2013 01:10:23 GMT
 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36
 DNT: 1
 Referer: http://0.0.0.0:3000/items/1/
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: en-US,en;q=0.8

Response:

 Date:Sat, 24 Aug 2013 00:27:56 GMT
 ETag:"d5098b2c3d1417da8ccd9764612248ca"
 Last-Modified:Thu, 08 Aug 2013 01:10:23 GMT
 Server:AmazonS3
 x-amz-id-2:gyR2VMt9hec8HrGvcXvDrrRb/sOm3i/WpUaRdnpr/PY2VoaJigSdA960B0q83zzN
 x-amz-request-id:434E3571705359E9

Thanks!

Upvotes: 3

Views: 1867

Answers (1)

russelll
russelll

Reputation: 61

Ok I figured out the problem. It's hard to debug because the browser doesn't give much info. It was a problem on the client side - the CORS specification is really picky about how a request is made. So in my case, I think the problem was loading the image in just an image tag.

The only way it seemed to work is if I set the "crossOrigin" attribute before loading the image:

 var grabbed = new Image();
 $(grabbed).attr('crossOrigin', '');
 $(grabbed).attr("src", mySource);

The only way I was able to debug this was to test several different setups on the client side & different configurations server side because the headers can be hard to interpret. (Problems on the client side can make it seem like the server isn't configured properly).

Upvotes: 3

Related Questions