Monday 12 June 2017

aws-sdk signed request response throwing syntax error

I'm trying to integrate direct uploads for images to S3 in my Heroku deployed application and following this guide by Heroku — Direct to S3 File Uploads in Node.js.

I've followed all the instructions in the guide correctly. On uploading an image in my form, I even get a 200 response with a responseText which is supposed to be parsed to JSON. The problem is that I get a syntax error when I open Chrome's developer tools and it also pauses the execution in the debugger.

Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.xhr.onreadystatechange (photo-upload.js:19)

The following is logged in my console which looks like valid JSON and should be parsed without any issue (dummy value for access key and signature):

{"signedRequest":"https://getfitapp.s3.amazonaws.com/my-pic.jpg?AWSAccessKeyId=DHQTJ126JKQ9DZLODQ9C&Content-Type=image%2Fjpeg&Expires=1497301502&Signature=AjwDHv2PvLUItEgGWtF2G5In2l0%3D&x-amz-acl=public-read","url":"https://getfitapp.s3.amazonaws.com/my-pic.jpg"}

Also, for reference, this is the function used to get a signed request from AWS before uploading the file:

function getSignedRequest(file){
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `/sign-s3?file-name=${file.name}&file-type=${file.type}`);
  xhr.onreadystatechange = () => {
    if(xhr.readyState === 4) {
      if(xhr.status === 200) {
        const response = JSON.parse(xhr.responseText);
        uploadFile(file, response.signedRequest, response.url);
      }
      else {
        alert('Could not get signed URL.');
      }
    }
  };
  xhr.send();
}

What might be the problem? Since the response is coming from AWS, I don't know what I can do to fix the problem.



via Daksh Shah

No comments:

Post a Comment