NoobSter NoobSter - 6 months ago 86
AngularJS Question

How to delete Amazon s3 file w/ nodejs / angular

var awsSdk = require('aws-sdk');

awsSdk.config = {
"accessKeyId": "key",
"secretAccessKey": "secret",
"region": "us-east-1"
}

var s3 = new awsSdk.S3({
accessKeyId: 'key',
secretAcessKey: 'secret'
});

exports.awsDelete = function(req, res){
s3.deleteObject({
Bucket: 'bucket',
Key: req.body.photo
}, function(err,data){
if (err) console.log('delete err', err);
console.log(data);
});
};


I can't figure out how to make this work (yet).

initially, I was getting a "no config" error, so I added the awsSdk.config json above. Now, it's just getting hung / pausing with no error. I am getting the expected key in req.body.photo.

My hunch is that i'm missing something in my config..

What am I missing / screwing up?




Update
I've added the code suggested below, but still no luck. I'll show how i'm passing my parameter:

updated code from answer below:

'use strict';

var aws = require('./aws');

var amazon = require('aws-sdk');

amazon.config = new amazon.Config();
amazon.config.accessKeyId = aws.key;
amazon.config.secretAccessKey = aws.secret;
amazon.config.region = aws.region;

var s3 = new amazon.S3();

exports.awsDelete = function(req, res){
var params = {
Bucket: aws.bucket,
Key: res.body.photo
};
s3.deleteObject(params, function(err, data) {
if (err) console.log(err)
else console.log("Successfully deleted myBucket/myKey");
});
};


route:

app.post('/awsDelete', uploads.awsDelete);


Front end Angular:

factory:

angular.module('clientApp').factory('Uploads', function($http) {
return {
delete: function(data){
console.log('delete fired');
return $http.post('/awsDelete', data);
}
};
});


angular controller:

angular.module('clientApp').controller('Distiller-editCtrl', function(Uploads){

$scope.item = {}

$scope.delete = function(){
Uploads.delete($scope.item).then(function(res){
console.log(res)
});
};
});





Seems it 'sort of works'. But something is making it take an extremely long time:

POST /awsDelete 200 120007ms


If I refresh the page, that causes it to successfully delete it as well.
Does anyone notice anything in my code that could be causing such a long response time.

Also, not getting the "successfully completed" console.log

Answer

I just tested this in node and it worked fine, obviously you need to put in your own accesskey, secretaccesskey, bucket and bucket key:

var AWS = require('aws-sdk'); 

AWS.config = new AWS.Config();
AWS.config.accessKeyId = "";
AWS.config.secretAccessKey = "";
AWS.config.region = "us-east-1";

var s3 = new AWS.S3();

var params = {
  Bucket: 'test537658ghdfshgfd', 
  Key: '1.png'
};

s3.deleteObject(params, function(err, data) {
    if (err) console.log(err)     
    else console.log("Successfully deleted myBucket/myKey");   
});
Comments