KTT
KTT

Reputation: 321

Google Cloud Storage: No 'Access-Control-Allow-Origin' header is present on the requested resource

I want to upload file to Google Cloud Storage. I created signed url using go. using signed url and axios, I write code like here.

      const options = {
        headers: {
          'Access-Control-Allow-Origin': '*',
        },
      }

      this.$axios
        .put(signed_url, file, options)
        .then((res) => {
          console.log(res)
        })
        .catch((err) => {
          console.log(err)
        })
    })

but response which is Access to XMLHttpRequest at 'https://storage.googleapis.com....' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. return after excute axios put. my backet cors setting is here.

❯ gsutil cors get gs://<backet-name>
[{"maxAgeSeconds": 86400, "method": ["*"], "origin": ["*"], "responseHeader": ["*"]}]

Upvotes: 1

Views: 3353

Answers (1)

Richard Varno
Richard Varno

Reputation: 547

Late to the party here, but posting this as it had me stumped for hours. I had this same problem, I solved it by setting the method and content type explicitly on both the client and in the function where the signed URL is generated.

SEVER SIDE CODE:

    bucket := "YOUR_BUCKET_NAME_HERE"
    filename := "someuniquefilename-uuid.png"
    method := "PUT"
    expires := time.Now().Add(time.Hour * 2) // allow 2 hours for large uploads
    ctp := "image/png"  // can also pass from client

    url, err := storage.SignedURL(bucket, filename, &storage.SignedURLOptions{
        GoogleAccessID: "[email protected]",
        PrivateKey:     []byte("-----BEGIN PRIVATE KEY-----\n  get this from your google service account \n-----END PRIVATE KEY-----\n"),
        Method:         method,
        Expires:        expires,
        ContentType:    ctp,
    })

CLIENT SIDE CODE:

    // get file data
    var file = $('#' + pfx + "File").prop("files")[0];

    $.ajax({
        method: "PUT",
        contentType: file.type, 
        processData: false,
        dataType: "xml",
        crossDomain: true,
        data: file,
        url: sURL,
        // headers: {'Access-Control-Allow-Origin':'*'},
        beforeSend: function (request){
            request.setRequestHeader("Access-Control-Allow-Origin", '*');
        },      
        xhr        : function ()
        {
            var jqXHR = null;
            if ( window.ActiveXObject )
            {
                jqXHR = new window.ActiveXObject( "Microsoft.XMLHTTP" );
            }
            else
            {
                jqXHR = new window.XMLHttpRequest();
            }

            //Upload progress
            jqXHR.upload.addEventListener( "progress", function ( evt )
            {
                if ( evt.lengthComputable )
                {
                    var percentComplete = Math.round( (evt.loaded * 100) / evt.total );
                    //Do something with upload progress
                    $('#' + pfx + "Progress").val(percentComplete); 
                    console.log( 'Uploaded percent', percentComplete );
                }
            }, false );

            return jqXHR;
        },  
        error: function (response, status, e) {
            alert('Oops something went wrong');
        },      
        success: function(data) {
            alert(data);
        },
        complete: function() {
            var a = 1;
        },
    
    });

    return false;

(and make sure your CORS is set on your google storage bucket)

Upvotes: 2

Related Questions