mardi 19 juillet 2016

Amazon S3 file upload: POST 405 Method Not Allowed using ember-uploader

I'm using ember-uploader to upload a file to Amazon S3. The component is very simple:

import Ember from 'ember';
import EmberUploader from 'ember-uploader';

export default EmberUploader.FileField.extend({
  signingUrl: '/sign',

  filesDidChange (files) {
    const uploader = EmberUploader.S3Uploader.create({
      signingUrl: this.get('signingUrl'),
    });

    uploader.on('didUpload', response => {
      console.log('Upload successful!');
    });

    if (!Ember.isEmpty(files)) {
      uploader.upload(files[0]);
    }
  }
});

I've then written a simple node express script that generates the pre-signed URL:

var aws = require('aws-sdk');
var config = new aws.Config({
  accessKeyId: 'ACCESS-KEY-ID', 
  secretAccessKey: 'SECRET-ACCESS-KEY', 
  region: 'us-east-1',
});
aws.config = config;
var bucketName = 'BUCKET-NAME';

var express = require('express');
var app = express();
app.use(fileUpload());
app.use(function(req, res, next) {
  req.headers['if-none-match'] = 'no-match-for-this';
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();    
});

app.get('/sign', function (req, res) {
  const s3 = new aws.S3();
  const fileName = req.query['name'];
  const fileType = req.query['type'];
  const s3Params = {
    Bucket: bucketName,
    Key: fileName,
    Expires: 60,
    ContentType: fileType,
    ACL: 'public-read'
  };
  s3.getSignedUrl('putObject', s3Params, (err, data) => {
    if(err){
      console.log(err);
      return res.end();
    }
    console.log('data =>', data);

    const returnData = {
      signedData: data,
      endpoint: `http://ift.tt/29QUA5k}`,
    };
    res.write(JSON.stringify(returnData));
    res.end();
  });
});

Whenever I try to upload a file, the component generates a POST request to http://ift.tt/29QWVBh

The response is 405 Method not Allowed

It's unusual as doing a PUT request makes this request work fine. However, ember-uploader only appears to do POST requests for s3 uploads.

My S3 bucket policy is:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "StmtXXXXXXX",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::ingagedtest2",
                "arn:aws:s3:::ingagedtest2/*"
            ]
        }
    ]
}

My S3 Bucket CORS Configuration is:

<CORSConfiguration>
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedHeader>*</AllowedHeader> 
  </CORSRule>
</CORSConfiguration>

I'm testing this on a http://localhost:3000 server. Any pointers in the right direction would be GREATLY appreciated! I cannot figure out what I am missing.




1 commentaire: